An Immediately-invoked Function Expression is a way to execute a function immediately, as soon as it is created. IIFE is an example of function invocation: the first pair of parenthesis (function(name) {...}) is an expression that evaluates to a function object, followed by the pair of parenthesis with parameters if any.
Let say we have a function to calculate a total from an array:
The simplest way is to create a function with a for..in loop to loop into each values of the array. Example:
function calculateTotal(arr) {
var total = 0;
for (var i in arr) {
total += arr[i];
}
return total;
}
calculateTotal([1,2,3,4,5,6]); // invoke the Javascript function for execution
How to construct the immediately-invoked function expression - IIFE?
- First wrap the whole function declaration into parenthesis
- Secondly add 1 more parenthesis at the end of the function.
- If there is any parameters to pass, pass them in the last parenthesis from step 2
- If there is any Javascript invocation like calculateTotal([1,2,3,4,5]);, please remove it.
1.
(function calculateTotal(arr) {
var total = 0;
for (var i in arr) {
total += arr[i];
}
return total;
}) // wrap the whole function into parenthesis
2.
(function calculateTotal(arr) {
var total = 0;
for (var i in arr) {
total += arr[i];
}
return total;
})() // add 1 more parenthesis here
3.
(function calculateTotal(arr) {
var total = 0;
for (var i in arr) {
total += arr[i];
}
return total;
})([1,2,3,4,5,6]) // pass parameters here
Top comments (0)