Concept of JavaScript Closure

Javascript closure is the very important concept of JavaScript. The closure allows programmers to write better code. We have already used closure much time but not able to identify that this is the closure. This is the common interview question for JavaScript developer.

What is closure?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

In a simple way closure is nothing but function inside other function which can access outer variables. Actually, the closure has three scope chains. It can access its own scope variables, Outer function variables, and it has also access to global variables.

Example: 

OR
Even closure can access outer function parameters as well.



Closure can also access the outer function variable after outer function return.
One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:
Please follow and like us:

You May Also Like

About the Author: Sujeet Kumar

Sujeet is Web and Android Devloper with a soft spot for functional programming. I like to play cricket, regular workout.

Leave a Reply

Your email address will not be published. Required fields are marked *