es6 IIFE
What is ES6 IIFE?
ES6 IIFE stands for Immediately Invoked Function Expression, which is a way of declaring and calling a function at the same time. It is commonly used in JavaScript to create a local scope and prevent variables from polluting the global scope.
How to use ES6 IIFE?
To use ES6 IIFE, you can declare a function expression and immediately invoke it using parenthesis. Here is an example:
(() => {
// code here
})();
In this example, we declared an arrow function expression, wrapped it in parenthesis, and called it immediately using another set of parenthesis. This creates a local scope where variables declared inside the function are not accessible outside of it.
You can also pass arguments to the IIFE by placing them inside the first set of parenthesis. Here is an example:
((x, y) => {
console.log(x + y);
})(2, 3);
In this example, we passed two arguments to the IIFE and logged the sum of them to the console.
Alternative ways to use IIFE
There are other ways to declare and call an IIFE in JavaScript. Here are some examples:
- Using a function expression instead of an arrow function
- Using the "function" keyword instead of an arrow function
- Using the "void" operator to prevent the IIFE from returning a value
Regardless of the syntax used, ES6 IIFE is a powerful tool in JavaScript that allows you to create local scopes and prevent variable collisions in the global scope.