What is IIFE (Immediately Invoked Function Expression) in Javascript ?
An IIFE (Immediately Invoked Function Expression) is a self-invoking javascript function it executes immediately upon definition, without requiring an explicit call. IIFEs are useful for creating private scopes, preventing variable conflicts, and encapsulating code. they provide a way to ensure that certain code runs immediately and independently, improving code organization and reducing global namespace pollution.
Example:-
(function() {
//write any code , it will automatically run
console.log("Hello world");
})();
this example involves an anonymous function wrapped in parentheses, immediately invoked with a final pair of parentheses. It executes instantly without requiring explicit calls elsewhere in the code.
let's see an other example-
(function(name) {
console.log("Hello, " + name + "!");
})("Diwakar");
in this example, the IIFE takes a "name" argument and logs a personalized greeting. the argument "Diwakar" is passed when invoking the IIFE.
use case:-
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