IIFE (Immediately Invoked Function Expressions) In Javascript

Vincent T.
0xCODE

--

In Javascript (JS), an IIFE (Immediately Invoked Function Expression) allows for immediate execution of functions, after it has been created.

We get the following benefits from IIFEs:

  • They don’t clog the global object with variables and functions
  • They are a simple way to isolate variable declarations

The following are syntax examples of an IIFE:

(function() {
/* */
})()

Here is another example using an arrow function =>:

(() => {
/* */
})()

The /* */ indicate where the function is written.

The Global Object Issue

When a function is created, it is added to the global object. Let us take the following code example:

function mult(x,y) {     
return x * y; }

This is a simple function called mult that takes in 2 parameters, variables x and y. It then returns the result as the product of the 2 variables.

The function, upon creation, is added to the window() global object. A variable declared outside of a function is also added to the global object.

var counter;

We can see the result or output using the console.log() command.

console.log(window.mult)
console.log(window.counter)

When you have declared many global variables and functions, the JS engine only releases allocated memory when the global object loses its scopes. This leads to the inefficient use of memory.

Another problem this can create is name collisions. This pollutes the global object, clogging it up and making the program less efficient.

IIFE As Expressions

We can also write functions as expressions. Using wrapping parentheses make a function, internally, considered an expression. A function expression does not require a name, so it does not need to be added to the global object. This allows execution without invoking a name.

For example, we can rewrite the code this way:

let mult = (function(x,y){     
return x * y;
})(3, 8);
console.log(mult);

We assign the function call to the variable called mult. This returns the answer which is 24.

Now lets create an IIFE using the general syntax by rewriting the code:

(function(x,y){         
return x * y;
})(3,8);

The function is created as an expression that executes immediately, without first having to be added to the global object.

Synopsis

Use IIFE to execute a function as an expression without requiring a name, thus helping to avoid collisions if functions have the same name from different programs. It minimizes adding functions and variables to the global object in memory. This makes the execution faster and memory usage more efficient. That affects the way a program works during critical moments.

--

--

Vincent T.
0xCODE

Blockchain, AI, DevOps, Cybersecurity, Software Development, Engineering, Photography, Technology