How to build Immediately Invoked Function Expressions in Javascript?

While I was exploring how to retrieve results from an asynchronous function in Angular , I stumbled upon a solution where the developer had used IIFE to retrieve the result :

It looked like this :

(async () => {
  console.log(await getData())
})()

This was confusing at first.

But after exploring IIFE the above code made sense.

First lets deep dive into IIFE.

Say you want to invoke a function only once in javascript.

You want to define the function and invoke it at the same time. Only once and never again.

Immediately Invoked Function Expression comes to the rescue.

Lets turn a normal function to an IIFE by following the below steps:

Step 1: Convert the function to a functional expression.

Consider the below code

function sayHello(){

   alert("Hello");
}

Lets convert it into an IIFE. First lets convert it into a functional expression.

All you have to do is cover the above function with parantheses:

(function sayHello(){

alert("Hello");
})

The functional expression is now ready.

STEP 2:

Immediately Invoke the above functional expression by adding () at the end of the function :

(function sayHello(){

  alert("Hello");
}) ()

That’s it our IIFE is ready.

The above code can be invoked only once.

But wait . Do we need to to do all this stuff just to say Hello.

Assume there are variables inside this function and you want to restrict their scopes within the function :

(function doMore(){

   var a = 10;
   var b = 10;

   console.log( a * b);

})()

In the above code the scope of the variables ‘a’ and ‘b’ are restricted to the function doMore() and also the scope of the function is limited to only one invocation. That’s the benefit of IIFEs.

The above code can be further simplified by removing the function name and ‘function’ keyword:

( () => {

var a = 10;
var b = 10;
console.log( a * b);

}) ()

A well prepared IIFE is now ready.

Going back to the piece of code I shared in the begining of the post,

the IIFE waits for an asynchronous method to return a value using ‘await’ keyword.

And since ‘await’ keyword can be used only by declaring the function as ‘async’ , an async IIFE is used

(async () => {
  console.log(await getData())
})()

There you go!


Posted

in

, ,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading