IIFE (Immediately-Invoked Function Expression in JavaScript)
1 min readApr 17, 2024
#4 JavaScript Series
It is a JavaScript function that runs as soon as it is defined. It’s a design pattern also known as a self-executing anonymous function.
Here’s an example:
(
function () {
console.log("Hello");
}
)();
You can also assign it to a variable for later use.
Usage:
- Avoids hoisting issues.
- Prevents global namespace pollution.
- Useful for creating modules.
@ Guess the Output
(
function (x) {
return (function(y){
console.log(x+y);
}
)(2)
}
)(1);
Output: 3
Explanation:
--------------
The outermost parentheses are used to wrap the entire function expression. This is a common practice to ensure the function is treated as an expression and not a declaration.
The outer function is immediately invoked with the argument 1. So, x inside the function becomes 1.
Inside the outer function, there's another immediately invoked function expression (function(y) { console.log(x + y); })(2). This inner function is immediately invoked with the argument 2.
Inside the inner function, y becomes 2. Then it calculates x + y, where x is from the outer function and y is from the inner function. So, x + y becomes 1 + 2, which is 3.
Finally, console.log(x + y) prints 3.