JavaScript Immediately Invoked Function Expressions (IIFE)
An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed immediately after being created. It is commonly used to create a new scope in JavaScript, preventing polluting the global scope with variables and functions.
IIFEs are useful for creating private variables, initializing configurations, and other scenarios where you want to execute code once and immediately.
Quick Links
What You'll Learn
In this tutorial, you'll learn what IIFE is, how to write one, and when it is useful. We'll also go over examples and exercises to help you understand IIFEs better.
Understanding Immediately Invoked Function Expressions (IIFE)
An IIFE is a function that runs as soon as it is defined. It is typically written using a function expression wrapped in parentheses followed by another pair of parentheses to invoke the function immediately.
Here's the basic syntax:
(function() {
// function body
})();
(function() {
// function body
})();
- (function() { ... }): This defines an anonymous function wrapped in parentheses, turning it into a function expression.
- (): The second set of parentheses immediately invokes the function.
By using IIFE, we avoid polluting the global scope and can create private variables within the function that are not accessible from the outside.
Example 1: Basic IIFE
Here's a simple example of an IIFE that logs a message to the console immediately after being defined:
(function() {
console.log("Hello from IIFE!");
})();
(function() {
console.log("Hello from IIFE!");
})();
What’s Happening Here:
- (function() { ... }): Defines the function.
- console.log("Hello from IIFE!");: The function runs immediately and logs the message.
- (): This immediately invokes the function.
The message is printed in the console immediately when the page loads.
Output:
Hello from IIFE!
Hello from IIFE!
Example 2: Using Parameters with IIFE
You can pass parameters into an IIFE, making it more flexible for different use cases.
(function(a, b) {
const sum = a + b;
console.log("The sum is:", sum);
})(5, 7);
(function(a, b) {
const sum = a + b;
console.log("The sum is:", sum);
})(5, 7);
What’s Happening Here:
- (function(a, b) { ... }): Defines the function with two parameters.
- const sum = a + b;: Adds the parameters and stores the result in a variable.
- console.log("The sum is:", sum);: Logs the result to the console.
- 5, 7: These values are passed into the IIFE immediately.
You can pass any values to the IIFE when it is invoked.
Output:
The sum is: 12
The sum is: 12
Example 3: IIFE with Private Variables
One of the most powerful uses of IIFEs is to create private variables that aren't accessible from the global scope.
const counter = (function() {
let count = 0;
return {
increment: function() {
count++;
console.log("Count is:", count);
},
decrement: function() {
count--;
console.log("Count is:", count);
}
};
})();
counter.increment(); // Count is: 1
counter.increment(); // Count is: 2
counter.decrement(); // Count is: 1
const counter = (function() {
let count = 0;
return {
increment: function() {
count++;
console.log("Count is:", count);
},
decrement: function() {
count--;
console.log("Count is:", count);
}
};
})();
counter.increment(); // Count is: 1
counter.increment(); // Count is: 2
counter.decrement(); // Count is: 1
What’s Happening Here:
- let count = 0;: This variable is private to the IIFE and cannot be accessed directly from outside.
- return { increment, decrement }: Returns an object with methods that can interact with the private count variable.
- Each time you call increment() or decrement(), it updates and logs the count.
Output:
Count is: 1
Count is: 2
Count is: 1
Count is: 1
Count is: 2
Count is: 1
Exercises
Try these exercises to practice writing and using IIFEs in different scenarios.
1. Write an IIFE that logs your name to the console.
// Exercise 1: Log name to console
(function() {
console.log("My name is John Doe.");
})();
// Exercise 1: Log name to console
(function() {
console.log("My name is John Doe.");
})();
2. Write an IIFE that takes two numbers and logs their multiplication result.
// Exercise 2: Multiply two numbers
(function(a, b) {
console.log("The product is:", a * b);
})(3, 4);
// Exercise 2: Multiply two numbers
(function(a, b) {
console.log("The product is:", a * b);
})(3, 4);
3. Write an IIFE that checks if a number is positive or negative.
// Exercise 3: Check if number is positive or negative
(function(num) {
if (num >= 0) {
console.log(num + " is positive or zero");
} else {
console.log(num + " is negative");
}
})(-5);
// Exercise 3: Check if number is positive or negative
(function(num) {
if (num >= 0) {
console.log(num + " is positive or zero");
} else {
console.log(num + " is negative");
}
})(-5);
Frequently Asked Questions
What is an IIFE in JavaScript?
What is an IIFE in JavaScript?
An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it is defined. It creates its own scope and helps avoid polluting the global namespace.
Why should I use an IIFE?
Why should I use an IIFE?
IIFEs help create private variables and prevent conflicts by isolating code inside its own scope. They're useful when you need to run a block of code immediately but don't want its variables to interfere with the global scope.
What is the syntax of an IIFE?
What is the syntax of an IIFE?
The common syntax is: (function() { ... })(). The first parentheses turn the function into an expression, and the second pair immediately invokes it.
Can IIFE accept parameters?
Can IIFE accept parameters?
Yes! You can pass arguments to an IIFE by including them inside the invoking parentheses, like: (function(name) { console.log(name); })(“John”);
Do IIFEs support arrow functions?
Do IIFEs support arrow functions?
Yes, IIFEs can be written using arrow functions: ((() => { ... })()); But be cautious—arrow functions do not have their own this context.
What's Next?
Next, you’ll explore recursion in JavaScript. You'll learn how recursive functions can simplify solving problems by breaking them down into smaller, manageable subproblems, leading to cleaner and more efficient code.