Loading lesson path
Concept visual
Start at both ends
is short for an Immediately Invoked Function Expression.
is a function that invokes itself when defined.
Normally, a function runs only when it is called. An IIFE runs automatically when the JavaScript engine reads it (compiles it).
(function () {// Code to run immediately
})();An IIFE function is defined and executed at the same time.
Everything inside an IIFE is private to that function.Variables inside an IIFE cannot be accessed from outside.
(function () {
let x = 10;
})();// x is not accessible here
(function () {
let hidden = 42;
})();
let result = hidden; // ⛔ Error: hidden is not defined(function () {
let text = "Hello! I called myself.";
})();Formula
The function above is also called an anonymous self - invoking function(function without name).
Formula
Function expressions can be made self - invoking.
A self - invoking function expression is invoked (started) automatically, without being called.Function function () {// Code to run
};Parentheses around the function tell JavaScript to treat the function as an expression.
(function () {// Code to run
});The function is wrapped in parentheses to turn it into an expression. Function expressions will execute automatically if the expression is followed by ().
(function () {// Code to run
})();() executes the function immediately.
Formula
You can only self - invoke a function expression.
You can not self - invoke a function declaration.You can pass arguments into an IIFE.
(function (name) {
let text = "Hello " + name;
})("John Doe");An IIFE can return a value, which can be stored in a variable.let result = (function () {
return 5 + 5;
})();Arrow functions can also be used as IIFEs.
(() => {
let text = "Hello! I called myself.";
})();