intermediate

Immediately Invoked Function Expressions

Learn about IIFE pattern for creating private scopes in JavaScript.

An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it is defined. This pattern was essential in older JavaScript for creating private variables and avoiding polluting the global scope. While modern ES6 modules have reduced the need for IIFEs, understanding them is important for working with legacy code and certain design patterns.

📚 Concepts & Theory

Basic IIFE Syntax

(function() {
    console.log("I run immediately!");
})();

With Arrow Functions

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

Passing Arguments

(function(name) {
    console.log(Hello, ${name}!);
})("Alice");

Returning Values

const result = (function() {
    return 42;
})();
// result = 42

Creating Private Scope

const counter = (function() {
    let count = 0;  // Private variable
    
    return {
        increment: function() { count++; },
        getCount: function() { return count; }
    };
})();

counter.increment();
counter.getCount(); // 1
// count is not accessible directly

Why Use IIFE?

  • Avoid polluting global namespace
  • Create private variables
  • Module pattern (before ES6 modules)
  • Execute code once immediately

🎯 Your Challenge

Create an IIFE that declares a private variable `secretNumber` set to 42, and returns an object with a method `getSecret` that returns the secret number.

📝 Starter Code

JavaScript
// Create an IIFE that returns an object with getSecret method
const vault = (function() {
    // Private variable
    
    
    // Return object with getSecret method
    return {
        
    };
})();

// vault.getSecret() should return 42
  • Wrap the function in parentheses: (function() {...})
  • Add () at the end to invoke immediately
  • Variables declared inside are private
  • Return an object to expose methods

Solution

JavaScript
const vault = (function() {
    const secretNumber = 42;
    
    return {
        getSecret: function() {
            return secretNumber;
        }
    };
})();

Explanation

The IIFE creates a closure where secretNumber is private. The returned object has a getSecret method that can access secretNumber through closure. External code cannot access secretNumber directly, only through getSecret().

⚠️ Common Mistakes to Avoid

  • Forgetting the wrapping parentheses around the function
  • Forgetting the () to invoke the function
  • Not understanding closure and private variables
  • Returning primitive instead of object for multiple methods

❓ Frequently Asked Questions

ES6 modules provide better scope isolation. However, IIFEs are still useful for inline scripts, creating closures, and working with legacy codebases.
Yes! (async () => { await someAsyncFunction(); })(); is a common pattern for top-level await in older environments.

🔗 Related Concepts