IIFE in JavaScript

An Immediately-Invoked Function Expression (IIFE) is a JavaScript design pattern that involves defining a function and then immediately executing it. It's a way to create a self-contained scope for your code, preventing variable leaks into the global scope, and it's commonly used in scenarios where you want to encapsulate logic, avoid naming conflicts, or perform one-time setup tasks.

(function() { // Your code here })();
  1. Function Declaration: (function() { ... }) defines an anonymous function enclosed in parentheses. This is important because in JavaScript, an expression is expected after the ( symbol, and a function declaration is a statement. Wrapping it in parentheses makes it an expression.
  2. Invocation: The final pair of parentheses at the end () immediately invokes the function. This means the code within the function block is executed immediately after its creation.

Basic IIFE

(function() { console.log("I am an IIFE!"); })(); // Output: "I am an IIFE!"

Encapsulation

var outsideVariable = "I'm outside!"; (function() { var insideVariable = "I'm inside!"; console.log(outsideVariable); // Accessible from the outer scope })(); console.log(insideVariable); // Error: 'insideVariable' is not defined

In this example, the IIFE creates a new scope, encapsulating the insideVariable and preventing it from leaking into the outer scope.

Passing Parameters

(function(name) { console.log("Hello, " + name); })("Alice"); // Output: "Hello, Alice"

Returning Values

var result = (function(a, b) { return a + b; })(10, 5); console.log(result); // Output: 15

In this example, the IIFE calculates the sum of two numbers and immediately returns the result.

Module Pattern

var counter = (function() { var count = 0; return { increment: function() { count++; }, getCount: function() { return count; } }; })(); console.log(counter.getCount()); // Output: 0 counter.increment(); console.log(counter.getCount()); // Output: 1

This example demonstrates the module pattern using an IIFE to create a counter with private state.

Conclusion

IIFEs have become less common with the advent of modern JavaScript features like block-scoped variables (let and const) and ES6 modules. However, they still offer a concise way to create isolated scopes and execute code immediately.