IIFE ( Immediately Invokable Function Expression )
Notes:
4. IIFE (Immediately Invokable Function Expression):
IIFE is a function that gets executed as soon as it is defined (i.e. immediately invoked or executed).
Self executable functions created using 2 pairs of parentheses i.e. ( )( );.
We pass a function definition in first pair of parentheses and pass required actual parameters list in second pair of parenthesis.
Syntax: /* function definition and call */
( function( [formal parameters list] )
{
statement(s);
[return retruningVaue;]
} )( [actual parameters list] );
Ex: /* a function without parameters, without returning value */
(function()
{
document.write("Hi");
})();
Ex: /* a function with parameters, with returning value */
var sum = (function(x,y)
{
return x+y;
})(2,3);
document.write(sum);
Example Code:
// Function declaration
function wishHi()
{
document.write("Hi","<br/>");
}
wishHi();
// IIFE
(function(){document.write("Hi","<br/>");})();
//Function declaration
function add(num1,num2)
{
return num1 + num2;
}
var sum = add(2,3);
document.write(sum,"<br/>");
//IIFE
var sum = (function(num1,num2){ return num1 + num2;})(2,3);
document.write(sum,"<br/>");
Interview Questions: