Open In App

What are IIFE (Immediately Invoked Function Expressions) ?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Immediately Invoked Function Expressions (IIFE) are JavaScript functions that are defined and immediately invoked. They are wrapped in parentheses to turn them into expressions and followed by an additional pair of parentheses to invoke them immediately after declaration.

Syntax:

(function() {
// IIFE body
})();

Key characteristics of IIFE:

  • They create a new scope, preventing variable hoisting and avoiding polluting the global scope.
  • They are used for encapsulating code and creating self-contained modules.
  • They are commonly used in scenarios where you need to execute some code only once, without polluting the global namespace.

Example: Here, the function is immediately invoked after its declaration, and the code inside it runs immediately. This pattern helps in keeping variables within a local scope and avoids conflicts with variables in the global scope.

Javascript




(function() {
    let message = 'Hello, World!';
    console.log(message);
})();


Output

Hello, World!

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads