Tuesday, February 7, 2017

ES6 Variables - 3


An immediately-invoked function expression (or IIFE, pronounced "iffy") is a JavaScript programming language idiom which produces a lexical scope using JavaScript's function scoping.
Runs itself immediately.

var name=“Arjun”;
//but Window has a name attribute too.
So we use IIFE
function(){
var name=“Arjun”;
}();

Let and const don’t need IIFE
{
const name=“Arjun”; //name is block scoped
}

for loop leaks its index variable.
for(var i=0;i<10;i++)
{
console.log(i); //prints 0 through 9
}
console.log(i); //prints 10 in global scope

If we have a time sensitive function in a for loop, the results may get skewed, unless we used an IIFE.
for(var i=0;i<10;i++)
{
setTimeout(function(){console.log(i);},1000); 
}
//prints 10, 10 times because in 1 sec the counter will have already run.
//replacing var with let prints out 0-9 because it acts like an IIFE.

IIFE

IIFE executes the function like it was assigned to a variable and run. It creates a function expression for the function and executes it. 

function test(){var name="Al";};
test();
//is the same thing as
(function(){var name="Al";})();
//The only difference is that the second one is executed instantly
//and the first one is executed when its name is called

IIFE Syntax
(function(){})();//is IIFE
!function(){}(); //is IIFE and returns true
-function(){}(); //is IIFE and returns NaN
$function(){}(); //is IIFE but requires JQuery
(function(){}();) //is IIFE

*IIFE produces lexical scope
*let and const behave like IIFE
*for loop does not leak

No comments:

Post a Comment