Saturday, September 18, 2021

IIFE(Immediately invocation function expression)

 Suppose we want to declare a variable that can not be accessed outside of a block ,that means we want a private variable then we can define a method and create a variable inside the method and then can call the method from outside .So, because of scope chain the variable cannot be accessed outside of the block .But there is a problem is that only to declare a private variable we are creating a whole function and it becomes unnecessary .So there is a new concept IIFE introduced.

Ex:

function game(){

var score = Math.random()*10; //Here score variable can't access from outside of the function.

console.log(score>=5);

}

game();


We can write above function using IIFE,

(function(){

var score = Math.random()*10; 

console.log(score>=5);

})();//calling the function .

normally if the function is annonymous and have body then javascript parser treat it as a function declaration .

But if we wrap this function into parentheses-() then javascript parser treat it as function expression .then we called it . Here score variable is no longer accessed outside of the scope.


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...