⏱ 0:03est. 5 min
Chapter 44- Immediately Invoked Functions Expressions (IIFEs)
Notes
Example 1
//function statement
function greet(name){
console.log(name)
}
//invoke it with following line
geet();
//function expression , creating function object on the fly
var greeFunc = function(name){
console.log(name);
}
//invoke it with following line
greetFunc();
//IIFE - Immediately invoked functions expression
Example 1
var greeting = function(name){
return name;
}(‘John');
console.log(greeting); // OUTPUT - John
Example 2
3; //this is a valid js expression, it will not throw error message
Example 3
"I'm a string" //this is also a valid js expression, it will not throw error message
Example 4
{
name : ‘john'
}
Example 5
//This will throw an error - unexpected token parenthesis
//REASON - Syntax parser expects it to be function statement
function (name){
return (name);
}
Example 6
//This will not throw any error,Everything inside parenthesis is assumed as expression so this will be treated as function expression. Here you are creating function object on the fly
(function (name){
return (name);
});
Example 7
Classic example of IIFE
//Writing a function expression and executing it on the fly
(function (name){
console.log("Inside IIFE" + name);
}(‘John'))
//OUTPUT : Inside IIFE John