iife arrow function

iife arrow function

If you are a JavaScript developer, then you might have come across the term IIFE (Immediately Invoked Function Expression) and arrow functions. These are two different concepts, but they can be used together in some cases.

An IIFE is a function that is immediately invoked after it is defined. It is usually used to create a local scope for variables and functions, so they don't interfere with the global scope. Here's an example of an IIFE:


(function() {
  var x = 10;
  console.log(x);
})();

This code creates an anonymous function that is immediately invoked. The variable x is defined inside the function, which means it is not accessible outside of the function.

Now, let's talk about arrow functions. An arrow function is a shorter way to define a function in JavaScript. It was introduced in ES6 (ECMAScript 2015). Here's an example:


const sum = (a, b) => {
  return a + b;
}
console.log(sum(3, 4)); // Output: 7

This code defines an arrow function called sum that takes two parameters (a and b) and returns their sum.

When we combine IIFE and arrow functions, we can create a self-invoking arrow function. Here's an example:


((a, b) => {
  console.log(a + b);
})(3, 4);

This code defines an arrow function that takes two parameters (a and b) and logs their sum to the console. The function is immediately invoked with the arguments 3 and 4.

Another way to write the same code is to use the IIFE syntax:


(function(a, b) {
  console.log(a + b);
})(3, 4);

Both of these examples will output the same result: 7.

In conclusion, IIFE and arrow functions are two different concepts, but they can be used together to create self-invoking functions. This can be useful in situations where you need to create a local scope for variables and functions.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe