Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the (function() { } )() construct in JavaScript?
The (function() { } )() construct is an immediately invoked function expression (IIFE). It is a function that executes immediately upon creation, without needing to be called separately.
Syntax
(function() {
// code
})();
The first pair of parentheses converts the function declaration into an expression:
(function(){...})
The second pair of parentheses immediately invokes that function expression.
Basic Example
(function() {
console.log("IIFE executed immediately!");
})();
console.log("This runs after IIFE");
IIFE executed immediately! This runs after IIFE
IIFE with Parameters
You can pass arguments to an IIFE by including them in the final parentheses:
(function(name, age) {
console.log(`Hello ${name}, you are ${age} years old`);
})("Alice", 25);
Hello Alice, you are 25 years old
Common Use Cases
1. Avoiding Global Scope Pollution:
(function() {
let privateVar = "This won't pollute global scope";
console.log(privateVar);
})();
// privateVar is not accessible here
This won't pollute global scope
2. Module Pattern:
const calculator = (function() {
let result = 0;
return {
add: function(x) { result += x; return this; },
multiply: function(x) { result *= x; return this; },
getResult: function() { return result; }
};
})();
console.log(calculator.add(5).multiply(3).getResult());
15
Alternative Syntax
Both syntaxes work identically:
// Method 1 (more common)
(function() {
console.log("Method 1");
})();
// Method 2
(function() {
console.log("Method 2");
}());
Method 1 Method 2
Conclusion
IIFEs are essential for creating private scope and avoiding global namespace pollution. They execute immediately and are commonly used in module patterns and library development.
Advertisements
