Header Ads Widget

Understand JavaScript Closure

 


Closure is a very important concept that every JavaScript developer should understand. In the post, I will provide a quick introduction of closure and then, I will be focusing on examples so that it will be easier for you to understand this concept. I will be sharing the video as well at the end of this post.

Note - I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.


What is a Closure?

As per MDN, "closure is the combination of a function bundled together(enclosed) with references to its surrounding state. In other words, a closure gives you access to an outer function's scope from an inner function".

With the above example, let's go through some examples to understand closure in details

Example 1

function sayHello() {
var message = "Hello World";
function sayItNow() {
console.log(message);
}
return sayItNow;
}

var returnFunc = sayHello();
returnFunc();

Output:
Hello World

Explanation:
In the above example, the outer function sayHello creates a variable message, which is then being used inside the inner function sayItNow. Within the inner function, there is no variable declared, but due to closure, it can access the variable declared within the outer function.

Example 2

function increment() {
var number = 10;
function printTheNumber() {
console.log(number);
}
number++;
return printTheNumber;
}

var returnFunc = increment();
returnFunc();

Output:
11

Explanation:
In the above example, the outer function increment creates a variable number, which is then being used inside the inner function printTheNumber. Within the inner function, there is no variable declared, but due to closure, it can access the variable declared within the outer function. 

Now when I am storing the inner function which is coming as the return value from the outer function in the variable returnFunc and finally using that to call the inner function. This time I am getting the value printer as 11 instead of 10 because the variable number is still valid even though the declaration of the inner function is completed.

Video


Conclusion

With the above two examples, one thing is clear that closure will allow us to access variables defined in the enclosed parent function(s) even when the enclosing functions finish execution. Every function has its own execution context, which comprises of an environment that gives life to any variable declared within that function and a reference to its parent's environment. A reference to the parent's environment makes all variables in the parent's scope available to all inner functions, regarding whether the inner functions are invoked outside or inside the scope in which they were created.

I hope this post will give you a clear picture of how closure works in JavaScript. Please provide your feedback in the comment section below.

Further Reading

Post a Comment

0 Comments