Search This Blog

2021/01/01

Immediately-invoked Function Expression (IIFE)

 An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created.

IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations.

Example 1:

(function (a)

{

console.log(a);

})(5)


Output:

5

or It can be defined as


(function() {

console.log("Hello from IIFE!");

}());


Output:

Hello from IIFE!



Assigning the IIFE to a variable stores the function's return value, not the function definition itself.

Example 2:

var func = (function ()

{

var a=10;

return a

})();

console.log(func)


output:

10


The variable within the expression can not be accessed from outside it.

Example 3:

var func = (function ()

{

var a=10;

return a

})();

console.log(a);



output:

ReferenceError: a is not defined


Another way of writing IIFE:

Example 4:

!function() {

console.log("Hello from IIFE!");

}();




Whenever JavaScript sees function keyword as the first word in a valid statement, it expects that a function definition is going to take place. So to stop this from happening, we are prefixing “!” in-front of the function keyword on line 1


The above variation can be used by replacing “!” with “+”, “-”, or even “~” as well. Basically any unary operator can be used.

e.g. following is also valid IIFE

Example 5:

~function() {

console.log("Hello from IIFE!");

}();


Example 6:


(function IIFE_initGame() {

// Private variables that no one has access to outside this IIFE

var lives;

var weapons;

init();


// Private function that no one has access to outside this IIFE

function init() {

lives = 5;

weapons = 10;

console.log(`lives: ${lives} and weapons: ${weapons}`);

}

}());


Output:

lives: 5 and weapons: 10


we have declared two variables inside the IIFE and they are private to that IIFE. No one outside the IIFE has access to them. Similarly, we have an init function that no one has access to outside the IIFE. But the init function can access those private variables.



No comments:

Post a Comment