Immediately Invoked Expressions
JavaScript IIFE
An Immediately Invoked Function Expression (IIFE) is a function that runs immediately after it is defined.
It is executed immediately, without being called.
What Is an IIFE?
Normally, a function runs only when it is called.
An IIFE runs automatically when the JavaScript engine reads it.
Example
(function () {
console.log("Hello World");
})();
The function above is defined and executed at the same time.
Why Use an IIFE?
IIFEs were commonly used to avoid creating global variables.
Everything inside an IIFE is private to that function.
Example
(function () {
let x = 10;
console.log(x);
})();
// x is not accessible here
How an IIFE Works
The parentheses tell JavaScript to treat the function as an expression.
The final () runs the function immediately.
Syntax
(function () {
// code here
})();
IIFE with Parameters
You can pass arguments into an IIFE.
Example
(function (name) {
console.log("Hello " + name);
})("John");
IIFE with Return Value
An IIFE can return a value, which can be stored in a variable.
Example
let result = (function () {
return 5 + 5;
})();
Arrow Function IIFE
Arrow functions can also be used as IIFEs.
Example
(() => {
console.log("Hello World");
})();
IIFE in Modern JavaScript
Today, JavaScript modules often replace the need for IIFEs.
Modules have their own scope by default.
Example
<script type="module">
let x = 10;
</script>
The variable x is scoped to the module and not global.
When is IIFE Used?
- To create a private scope
- To run setup code once
- In older JavaScript code
When Not to Use IIFE
- When using modern JavaScript modules
- When simpler code is sufficient
Common Mistakes
- Forgetting the final parentheses
Without (), the function will not run. - Confusing IIFE with normal functions
IIFEs cannot be called again. - Overusing IIFEs
Modern JavaScript often does not need them.
End of Functions Section
You have now learned the most important concepts about JavaScript functions.
Try the quiz to test your knowledge.