Javascript - Immediately invoked function expression (IIFE)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

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)

Advertising

3 - Example

3.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 */ 
)

3.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);

web/javascript/es/iife.txt · Last modified: 2019/06/05 12:39 by gerardnico