What is IIFE (Immediately Invoked Function Expression) in Javascript ?

DiwakarDiwakar
1 min read

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

Github-https://github.com/DIWAKARKASHYAP

10
Subscribe to my newsletter

Read articles from Diwakar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Diwakar
Diwakar

As a passionate developer, I thrive on acquiring new knowledge. My journey began with web development, and I am now actively engaged in open source contributions, aiding individuals and businesses.