Javascript - Immediately invoked function expression (IIFE)

1 - 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)

3 - Syntax


(function() {
    var localVariable = globalVariable
    ... = function() { return localVariable; };
})();

// Equivalent to
(function(localVariable) {
       result[globalVariable] = function() { return localVariable; };
})(globalVariable);

4 - Example

4.1 - 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 */ 
)

4.2 - 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);



Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap