An IIFE, or Immediately Invoked Function Expression, is a JavaScript function that executes immediately after it is defined. It provides a way to create self-contained blocks of code that don't interfere with the global scope. By invoking the function immediately, it allows for encapsulation and private variable scope.
(function() {
//write any code , it will automatically run
console.log("Hello world");
})();
in this example, an anonymous function is defined and invoked immediately by wrapping it in parentheses. It executes instantly without requiring explicit invocation elsewhere in the code.
(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
Top comments (0)