Javascript immediately invoked function expression

This is a very simple immediately invoked function expression (IIFE) in javascript. The function itself is defined inside a parenthesis with another pair of empty parenthesis immediately followed next to it, and it makes the function to execute immediately.

(function(){
	console.log("Hello, This is a immediately invoked function expression!");
})();

The IIFE is assigned to the variable a, the value of x is passed into this IIFE, the IIFE pass the value of x to a new variable i, then it returns a function that in turn returns the value of i.

var x=1;
var a = (function(i){//i will hold the value of passed variable 
	return function(){return i};
})(x);//pass x into the function
x = 2;
console.log("Printing what's in a: "+a); // function (){return i} 
console.log("Calling a() will return: "+a()); // 1
console.log("Calling a(1) will return: "+a(1)); // 1
console.log("Calling a(2) will return: "+a(2)); // 1
console.log("Calling a(3) will return: "+a(3)); // 1
console.log("Calling a('sdf') will return: "+a("sdf")); // 1
console.log("Calling a() with any value inside the parenthesis will return:"+a()); // 1

Search within Codexpedia

Custom Search

Search the entire web

Custom Search