A logo showing the text blog.marcnuri.com
Español
Home»JavaScript»What is an Immediately Invoked Function Expression (IIFE)?

Recent Posts

  • Fabric8 Kubernetes Client 7.2 is now available!
  • Connecting to an MCP Server from JavaScript using AI SDK
  • Connecting to an MCP Server from JavaScript using LangChain.js
  • The Future of Developer Tools: Adapting to Machine-Based Developers
  • Connecting to a Model Context Protocol (MCP) Server from Java using LangChain4j

Categories

  • Artificial Intelligence
  • Front-end
  • Go
  • Industry and business
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • August 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • January 2017
  • December 2015
  • November 2015
  • December 2014
  • March 2014
  • February 2011
  • November 2008
  • June 2008
  • May 2008
  • April 2008
  • January 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

What is an Immediately Invoked Function Expression (IIFE)?

2011-02-19 in JavaScript tagged JavaScript / Frontend by Marc Nuri | Last updated: 2025-01-28
Versión en Español

JavaScript, as a language, offers a variety of patterns and techniques to structure and execute code. One such technique is the Immediately Invoked Function Expression (IIFE). If you've ever wondered what an IIFE is, how it works, and why it exists, this post is for you.

The basics of IIFE

An Immediately Invoked Function Expression is a JavaScript function executed immediately after it is defined. The general syntax looks like this:

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

The function is defined and executed right away. It is defined inside a pair of parentheses (function() { ... }) to ensure it is treated as an expression rather than a declaration. The final pair of parentheses () at the end of the expression are used to invoke the function immediately.

Key characteristics of IIFE

  • Immediate execution: The function is run as soon as the JavaScript engine encounters it.
  • Encapsulation and Isolation: The function creates a private scope, which helps avoid polluting the global scope. Variables declared inside the IIFE are not accessible from outside the function.
  • Self-contained modules: IIFEs can act as mini-modules by returning objects or functions that maintain a private internal state while exposing only chosen methods or values.

Why use an IIFE?

IIFEs are commonly used in JavaScript to:

1. Avoid global variables

JavaScript variables declared with var can potentially pollute the global namespace. An IIFE creates a new scope, isolating the variables inside it from the rest of the code.

(function() {
    var message = "Hello, IIFE from blog.marcnuri.com!";
    console.log(message); // "Hello, IIFE!"
})();

console.log(typeof message); // "undefined"

In this example, the message variable is not accessible outside the IIFE.

2. Creating private variables

IIFEs are useful for creating private variables and encapsulating logic. This is particularly helpful when building modular code.

var store = (function () {
    var items = [];

    return {
        addItem: function(item) {
            items.push(item);
        },
        getItem: function(index) {
            return items[index];
        },
        getItemCount: function() {
            return items.length;
        }
    };
})();

store.addItem("blog.marcnuri.com");
console.log(store.getItem(0)); // "blog.marcnuri.com"

Here, the items variable is private and can only be accessed or modified through the returned object.

3. Executing initialization code

IIFEs are a useful and clean way to run setup code without leaving behind temporary variables or functions that clutter the global scope.

(function() {
    console.log("blog.marcnuri.com initialized");
    // Perform setup tasks without polluting the global scope
})();

Common use cases for IIFE

  • Module pattern: IIFEs are often used to create modules in JavaScript. The "Creating private variables" example above demonstrates this.
  • Polyfills: IIFEs can be used to create polyfills for older browsers.
    polyfill.js
    (function() {
      // Polyfill for Array.prototype.forEach
      if (!Array.prototype.forEach) {
        // Implementation of Array.prototype.forEach in case it doesn't exist
        Array.prototype.forEach = function(callback, thisArg) {
          for (var i = 0; i < this.length; i++) {
            callback.call(thisArg, this[i], i, this);
          }
        };
      }
    })();
  • Event handlers: IIFEs can be used to create isolated event-handling logic.
    event-handler.js
    (function() {
      // Attach event listener to a button
      var blogButton = document.getElementById("blogButton");
      blogButton.addEventListener("click", function() {
        console.log("Button clicked!");
      });
    })();
  • One-time scripts: IIFEs are useful for running one-time scripts that don't need to be reused.
    one-time-script.js
    (function() {
      // One-time script to log a message
      console.log("This script runs only once and never again");
    })();

Conclusion

IIFEs are a powerful and versatile pattern in JavaScript. They demonstrate how JavaScript's flexibility allows developers to create clean, modular, and maintainable code. By using IIFEs, you can avoid polluting the global scope, create private variables, and execute initialization code cleanly and concisely.

References

  • Ben Alman: Immediately-Invoked Function Expression (IIFE)
  • MDN Web Docs: IIFE
  • Wikipedia: Immediately Invoked Function Expression
Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Post navigation
What is a Java Heap dump?BeansBinding Performance (Issue 37)
© 2007 - 2025 Marc Nuri