Functions in js:
Functions are nothing but a block of reusable code. used to simplify the whole codebase. let us discuss with an example and realize the syntax.
//write a function to geet someone:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("javascript");
// Output: Hello, javascript!
here in the above block of code "name " is the parameter and "javascript" is known as arguments. Both can be one or more than one.
In ES6 a new form was introduced known as arrow function:
//write a function to add tow number in js
const add = ((a,b)=>{
return a+b;
})
console.log(add(2,3));
//output 5
Arrow functions have a shorter and more concise syntax compared to traditional function expressions, which makes it more cleaner and readable.
IIFE:
IIFE stands for immediately invoked function expression . It is a design pattern in javascript where a function is defined and immediately invoked(called) right after the declaration. This pattern is basically used to create a local scope for the variables and avoid polluting the global scope.
lets see the syntax:
// fuction to greet the user
(function(name) {
console.log("Hello, " + name + "!");
})("javascript");
//output : Hello, javascript!
It is commonly used to encapsulate the code ,prevent naming conflicts and control variable scope. Before ES6 it was so popular but it decreased
the introduction of block-scoped variables with "let" and "const" in ES6, as they provided a way to create private variables within a function scope. But it is still relevant while working with old Javascript codebase.
This is for today , keep practicing.
Subscribe to my newsletter
Read articles from Jeet kangsabanik directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Jeet kangsabanik
Jeet kangsabanik
I am jeet , experienced full-stack developer proficient in HTML, CSS, JavaScript, React, MongoDB, MySQL, and Express.js. Dedicated to creating innovative and robust web applications with a keen eye for design and a commitment to delivering high-quality, scalable solutions that meet and exceed client expectations.