DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on • Edited on

What is IIFE in Javascript ? (important interview question)

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");
})();
Enter fullscreen mode Exit fullscreen mode

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");

Enter fullscreen mode Exit fullscreen mode

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

Github-https://github.com/DIWAKARKASHYAP

Top comments (0)