Javascript - Immediately invoked function expression (IIFE)
Table of Contents
About
An IIFE (pronounced “iffy”) is a function expression that is immediately invoked in order to create a local scope for the variables
They therefore won’t affect the surrounding code outside of it - the global scope particularly
They are used as the basic construct of global library to create a private scope.
Articles Related
Syntax
(function() {
var localVariable = globalVariable
... = function() { return localVariable; };
})();
// Equivalent to
(function(localVariable) {
result[globalVariable] = function() { return localVariable; };
})(globalVariable);
Example
Basic with parameters
- A basic function expression
funcExp = function (x, y) { return x + y; } ;
console.log(
/* Parentheses means execute: here the function expression */
funcExp(2,3) /* Pass the variables 2 and 3 */
)
- The same function expression but as an IIFE
console.log(
/* Parentheses means execute: here the function expression */
( function (x, y) { return x + y; } )(2,3) /* Pass the variables 2 and 3 */
)
Scope creation
An IIFE is often used to create a scope in order to declare variables that won’t affect the surrounding code outside of it.
var foo = "foo from Global";
(function IIFE(){
var foo = "foo from IIFE";
console.log( foo );
})(); // "Hello!"
// The foo global variable was not affected by the foo variable in the IIFE
console.log(foo);