Immediately Invoked Function Expressions (IIFE) (Live Playground)
In this tutorial, we will explore Immediately Invoked Function Expressions (IIFE) in JavaScript, which allow you to create a new scope for variables and execute code immediately upon declaration.
What is an IIFE?
An Immediately Invoked Function Expression (IIFE) is a function that is both declared and executed at the same time. This can be useful when you want to create a new scope for variables and execute a piece of code without polluting the global scope.
(function () {
console.log('Hello, I am an IIFE!');
})();
The function is wrapped in parentheses, which makes it an expression, and it is immediately followed by another set of parentheses, which executes the function.
Creating Private Scopes with IIFE
One of the primary uses of IIFE is to create a new scope for variables, preventing them from polluting the global scope. This can be particularly helpful when working with third-party libraries or when you want to prevent naming collisions.
(function () {
let privateVar = 'I am a private variable.';
console.log(privateVar); // Output: I am a private variable.
})();
console.log(privateVar); // Output: Uncaught ReferenceError: privateVar is not defined
Returning Values from IIFE
You can also return values from IIFE, which can be useful when you want to assign the result of an expression to a variable.
const result = (function () {
return 2 + 3;
})();
console.log(result); // Output: 5
Passing Arguments to IIFE
You can pass arguments to IIFE just like you would with regular functions. This can be helpful when you want to use IIFE to perform a specific task with given inputs.
(function (name) {
console.log('Hello, ' + name + '!');
})('John'); // Output: Hello, John!
Conclusion
Immediately Invoked Function Expressions (IIFE) are a powerful feature in JavaScript, allowing you to create new scopes for variables and execute code immediately upon declaration. This can help you prevent naming collisions, keep your code organized, and maintain clean global scope. By understanding IIFE, you can write more efficient and maintainable JavaScript code.