0
0
JavascriptConceptBeginner · 3 min read

What is IIFE in JavaScript: Explanation and Example

An IIFE (Immediately Invoked Function Expression) in JavaScript is a function that runs right after it is defined. It helps create a private scope to avoid polluting the global space by wrapping code inside a function that executes immediately.
⚙️

How It Works

Think of an IIFE like a self-starting machine. You write a function, then immediately turn it on without waiting or calling it later. This function runs once and creates its own private space where variables and code live without affecting the outside world.

This is useful because JavaScript normally shares variables globally, which can cause conflicts. The IIFE wraps code inside parentheses to treat it as an expression, then adds parentheses at the end to run it right away. It's like wrapping a gift and opening it immediately to use what's inside without leaving a mess outside.

💻

Example

This example shows an IIFE that prints a message immediately and keeps its variable hidden from the outside.

javascript
(function() {
  const message = 'Hello from IIFE!';
  console.log(message);
})();
Output
Hello from IIFE!
🎯

When to Use

Use an IIFE when you want to run code once without leaving variables or functions in the global space. It is helpful for:

  • Creating private variables that won’t clash with others.
  • Running setup code immediately when a script loads.
  • Keeping your code clean and avoiding accidental overwrites.

For example, when loading a script on a webpage, an IIFE can initialize settings without exposing internal details to other scripts.

Key Points

  • An IIFE runs immediately after it is defined.
  • It creates a private scope to protect variables.
  • It helps avoid polluting the global namespace.
  • Commonly used for initialization and modular code.

Key Takeaways

An IIFE is a function that runs right after it is created to keep variables private.
It helps prevent conflicts by not adding variables to the global scope.
IIFEs are useful for running setup code immediately and keeping code clean.
The syntax uses parentheses to wrap the function and invoke it instantly.