DEV Community

Abuabdurrahman Abdulbasit
Abuabdurrahman Abdulbasit

Posted on • Updated on

JavaScript Immediately invoked Function Expression (II Don noFE)?

JS IIFE

What is IIFE?

So you have been hearing IIFE and have been wondering, what is this IIFE?
Well, worry no more!

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

How does a normal functions looks like?

   function multiply() {
 var x = 20;
 var y = 20;
 var answer = x * y;
 console.log(answer);
 }
multiply(); 
Enter fullscreen mode Exit fullscreen mode

This function simply multiplies together the values of x and y. We then call the functions shortly after.

Why then do we need IIFE?

The most common use case for IIFE is to create a closure with some private variables inside it.

The above function can be be reused anytime we want to. We can just do that by calling the function multiply().

What if that is not what we want? What if we simply want to call a function in order to get an output, not to reuse it?
We would not want our program to ever be able to accidentally access it. We would not want to pollute the global object.
That is when IIFE comes into play.

How do we then write an IIFE?

It's simple!
Let's take it from the name:

Function expression

To make a function to be a function expression, we declare it inside parentheses like this:

(function () {
    statements
});
Enter fullscreen mode Exit fullscreen mode

Immediately Invoked

To make it immediately invoked, we append () to the function expression.

(function () {
    statements
})();
Enter fullscreen mode Exit fullscreen mode

We basically have a function defined inside parentheses, and then we append () to execute that function.

-The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
-The second part creates the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.

We can rewrite our multiply function using IIFE

  (function multiply() {
 var x = 20;
 var y = 20;
 var answer = x * y;
 console.log(answer);
 })();
Enter fullscreen mode Exit fullscreen mode

This will immediately call the function

Assigning IIFE to a variable

We can assign an IIFE to a variable.This will store the function's return value, not the function definition itself.

var result =  (function multiply() {
 var x = 20;
 var y = 20;
 var answer = x * y;
 console.log(answer);
 })();
Enter fullscreen mode Exit fullscreen mode

And then we can have the result like this:

 result;
 //400
Enter fullscreen mode Exit fullscreen mode

This is my first post on dev.to 😁. Hope you like it.

Top comments (2)

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei

Thanks. Great Article.

Collapse
 
abuabdu46060974 profile image
Abuabdurrahman Abdulbasit

Thanks!!