Skip to content

IIFE (Immediately Invoked Function Expression)

Published: at 11:00 AM

IIFE, short for Immediately Invoked Function Expression, is a fancy way of saying “function that runs as soon as it’s defined.”

Here’s the breakdown:

Why use IIFE?:

How it looks:

Imagine a party happening inside parentheses:

(function () {
  // Code to be executed immediately
})();

The function is defined, wrapped in parentheses, and then immediately invoked by the second pair of parentheses.

Example of IIFE:

(() => {
  console.log("IIFE");
})();
// output "IIFE"

IIFE is used to avoid polluting the global scope. It’s a good practice to wrap your code in an IIFE to avoid polluting the global scope.

(() => {
  const foo = "Foo";
  console.log(foo); // output "Foo"
})();

console.log(foo); // Uncaught ReferenceError: foo is not defined

IIFE is also used to create a new scope for your variables. This is useful when you want to avoid variable hoisting.

(() => {
  console.log(foo); // undefined
  var foo = "Foo";
  console.log(foo); // output "Foo"
})();