EasyFunctions📖 Theory Question

What is an IIFE (Immediately Invoked Function Expression) and when do you use it?

💡

Hint

Defined and called immediately — creates a private scope

Full Answer

An IIFE is a function that is both defined and invoked immediately. It creates an isolated scope.

// Classic IIFE syntax
(function() {
  const private = 'inaccessible outside';
  console.log(private);
})();

// Arrow IIFE
(() => {
  // isolated scope
})();

// IIFE with parameters
(function(global) {
  global.myLib = {};
})(window);

// IIFE returning a value
const result = (() => {
  const x = computeExpensiveThing();
  return x * 2;
})();

Use cases:

  • Avoid polluting global scope (classic library pattern)
  • Create truly private variables (module pattern)
  • Capture loop variables (pre-let closure fix)
  • One-time initialization logic
💡 In modern JS, ES modules and block-scoped let/const make IIFEs less necessary. But they're heavily used in legacy code and still valid for specific patterns.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint