IIFE And Closures

IIFE also known as Immidiately Invoked Function Expressions. Let’s understand this with help of an example.

Consider we want to build a game. In this game we win a game if score >=5<9 and lose the game if score <5. But we want to keep score hidden in this game.

We can do this using a simple function, as we know the variables defined inside the function cannot be accessed from the outside scope. Therefore, we can write something like this

We can do this in a more better way using IIFE as there are few problems with the above solution. If the only motive is to hide the score variable from the outside, which means creating a private variable, then we do not need to declare a variable function with a name and then call it.

Let’s write an IIFE

How does this work ?

If we write a simple statement

function () {

}

Then Javascript parser will think that it is a function declaration. But since we do not have a name for the function declaration, then it will throw an error. So we need to trick the parser and make it believe that we have here a expression and not a declaration. Solution to this is to wrap the entire code into parenthesis (). Which is known as IIFE. And post that we called the function using ().

This is how we have created a data privacy here as score variable is not accessible to the outside scope.

CLOSURES

This is one of the crucial and advanced things of Javascript. Let’s jump directly into practical to understand closures.

Till now we have created a function which calculate how many years we have left in retirement. Let’s take help of that example toi understand closures.

Let’s now call this function to understand closures. As we have already know that this function will return a function which we will store in a variable, and then the variable will act as function as well.

Detailed Analysis

Let’s have a look at what happened exactly.

  • So we started by calling our retirement function
  • Function then declares the ‘a’ variable and returns a function
  • Then the function finishes and its execution context gets poped out of the stack
  • We have used variable ‘a’ and retirementAge variable in the inner function which is available in the outside function, and if we run this it still works
  • This means we are able to still use the variables of the outside function, even after the retirement function which declares the variables already stopped its execution

This is Closure.

Let’s take one other example which we have covered earlier to understand closures.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts