What is IIFE (Immediately Invoked Function Expression) in Javascript ?
10 July, 2023
0
0
0
Contributors
An IIFE (Immediately Invoked Function Expression) is a self-executing JavaScript function that runs as soon as it is defined. It provides a way to create a private scope for variables and encapsulate code, preventing conflicts with other parts of the program. By immediately invoking the function, it allows for immediate execution and enhances code organization and encapsulation.
(function() {
//write any code , it will automatically run
console.log("Hello world");
})();
in this example, An anonymous function is defined and wrapped in parentheses. The final parentheses immediately invoke the function, causing it to execute without explicit external calls.
let's see an other example-
(function() {
var message = "Hello, world!";
console.log(message); // Output: Hello, world!
})();
console.log(message); // Error: message is not defined
In this example, the message variable is limited to the IIFE's scope and inaccessible outside. Accessing it externally triggers an error.
Use Cases-
1- Avoiding global namespace pollution
2- compatibility with older javascript
3- Encapsulating code
4- Modular Pattern
Thank you for reading, please follow me on Twitter, i regularly share content about Javascript, and React and contribute to Opensource Projects
Twitter-https://twitter.com/Diwakar_766