DEV Community

Shane Plasebo
Shane Plasebo

Posted on

How to create an immediately-invoked function expression - IIFE in Javascript

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
Enter fullscreen mode Exit fullscreen mode

How to construct the immediately-invoked function expression - IIFE?

  1. First wrap the whole function declaration into parenthesis
  2. Secondly add 1 more parenthesis at the end of the function.
  3. If there is any parameters to pass, pass them in the last parenthesis from step 2
  4. 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
Enter fullscreen mode Exit fullscreen mode

2.

(function calculateTotal(arr) {
var total = 0;
for (var i in arr) {
  total += arr[i];
}
return total;
})() // add 1 more parenthesis here
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)