Understanding JavaScript Closure

Harshit Anand
2 min readAug 6, 2021

I started learning JavaScript a few days back. After learning the basic syntax of JS, I switched over to the most popular course on JavaScript. You might have guessed it — “Namaste JavaScript by Akshay Saini”.
My sole purpose in writing this blog is to improve my writing skills and understanding of JavaScript because when you write what you learn, it stays with you for a longer time.

Closure is defined as a combination of a function bundled together with its lexical environment. Confused?? Let’s dive deep into it.
Check the following code snippet:

function x(){    var b =10;    function y(){        console.log(b);    }    y();
}
x();

The functionx() creates a local variable b and a function y(). The y() function is an inner function that is defined inside x() and is only accessible inside the body of the function x(). The output of the above program is 10.
Now consider another code snippet:

function x(){    var b =10;    function y(){        console.log(b);    }    return y;
}
var z = x();
z();

Running this code has exactly the same output as that in the previous snippet.
What’s different is that the function x() returns the inner function y(). At first, we would think about how the output of both the code is same! Once x() finishes its execution we might expect that b variable is no longer accessible. And why not we should expect? In most programming languages, it happens exactly the same. We can’t access the local variable inside the function after function execution is over. But JavaScript is different from other programming languages. The reason is that functions in JavaScript form closures.
A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, z can access the lexical environment of y() i.e. it has the reference to the variable b. So, when z() is invoked, the variable b remains available for use.

https://www.youtube.com/watch?v=uH-tVP8MUs8&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=8
To understand lexical scoping watch this video.

--

--