You are currently viewing What is IIFE in JavaScript with Example| Create a Function

What is IIFE in JavaScript with Example| Create a Function

IIFE Javascript Example

In this article, we will see IIFE(Immediate Invokable Function Expression) in javascript with an example. We know that there are many ways in which we can create or define a function in javascript. We can create a javascript function using function declaration, function expression, funciton constructor as well as IIFE which is Immediate Invokable Function Expression.

IIFE (Immediate Invokable Function Expression)

An IIFE is a function that gets executed as soon as it is defined.

IIFE is also known as self-executable functions, it is created using 2 pairs of parentheses i.e.()()
We pass a function definition in the first pair of parentheses and pass the required actual parameters list in the second pair of parentheses.

Syntax: Function definition and call

(function([formal parameters list])
{
statement(s);
[return returning value;]

})([actual parameters list]);

Here syntax, first we open the parentheses and then write the “function” keyword. Then in pair of parenthesis will be passed “formal parameters list”, which is optional. And in the body of the function, we write a set of statements for execution. In the second pair of parentheses, we pass the “actual parameters list”. The parameters that we write in the function definition are called formal parameters whereas the parameters that we pass function are called actual parameters. So, the second pair of parameters indicates we are calling the function.

Example code

Function without parameters, without returning value

(function(){
document.write("HI");
})();

/*
output:
HI
*/

In the above example code, we set the first parentheses to empty, so this is without a parameter function. And we print the “HI” message inside the function then we call the function using empty parentheses () after closing the function parentheses. Hence, the message “HI” is displayed in the output.

READ ALSO  Click on The Image to Enlarge in JavaScript

Function with parameter and returning value:

var sum = (function (num1, num2)
{
return num1 + num2;
})(45,45);

document.write(sum)
/*
output:
90
*/

In the above code, We store the return value to the variable name “sum”. We pass two parameters namely num1, num2 then we add both values ​​and return. We give the value 45 to num1 and 45 to num2, so it will add and return the value “90”.

Leave a Reply