JavaScript Function Closures

I don't know how to emphasise how much closures are important 🙂 but if you are not aware of it, you may face many unpredictable and unexpected issues in your code. Even you are aware of it, you may still have some logical problem due to "Function Closure"

A function can access all variables defined inside the function, like below code:

A function can also access variables defined outside the function, like the following code.

if one variable is defined outside and inside(private) the function with the same name, they are different variables.

A Counter Dilemma

Counter dilemma is a well known case in JavaScript. Let's say we need to use a variable for counting something, and we want this counter variable to be available to all functions.

First way (unsafe and unexpected result) but it is working 🙂

We could use a global variable, and a function to increase the counter variable, like below code:

This code is working but any code on the page can change the counter variable, without calling add(). This may result in unexpected behaviour of code.

Second Way (local variable usage) this is not working

We could define a counter variable inside add() function, to prevent other code from changing it:

It did not work because we display the global counter variable instead of local counter variable.

Third Way (returning local variable value) this is not working

Let's remove global counter variable and access local counter variable by letting the function return it:

It didn't work because we reset local counter variable every time we call the function.

Fourth way (Nested Function usage) this is not working

This could have solved our problem, if we could reach the plus() function from the outside.

Fifth Way (Closure usage) it is working properly 🙂

We should use self-invoking functions (IIFE)

The self-invoking (IIFE) functions only run once.

It sets the counter to zero, and returns a function expression. This returned function expression can access counter variable in the parent scope. This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

The counter variable is protected by the scope of the anonymous function, and can only be changed using the add function.

Leave a Reply