Closures and Lexical Scoping in JavaScript

Amitav Mishra
Oct 8 · 2 min read
Image for post
Image for post
Photo by Markus Spiske on Unsplash

Variables in JavaScript have two types of scoping i.e. Local and Global scope. If any variable is declared inside a function, then it is a local variable and if the variable is declared outside the function then it is global variable. The scope of variables is defined by their position in the code.

Lexical Scope

JavaScript follows Lexical scoping for functions. Lexical scope means any child’s scope has access to the variables defined in parent’s scope i.e. inner functions can access the global variables.

var a = 5;function sum() {
return a + 6;
}
console.log(sum()); // 11

In the above example, function sum() is using global variable "a" to perform the addition. That means variable "a" is in scope of sum().

Closure

var a = 5;function sum() {
return a + 6;
}
console.log(sum()); // 11

A Closure is a function which has access to the parent scope variables. The above function has access to global variable “a”, so it is a closure.

If you will do console.dir(sum), then you can see inside [[scopes]] property, the global variable “a” is present. It means function sum() has access to the variable “a”. Check the below snippet.

jscurious.com

Now let’s see another example of Closure with respect to inner function.

function sum(outerValue) {
return function(innerValue) {
return outerValue + innerValue;
}
}
const findSum = sum(5);console.log(findSum(10)); // 15

When you call sum(5), it returns a function which holds the variable outerValue. So when you call findSum(10), it adds the outerValue value with innerValue value.

The inner function holds the outerValue even after the outer function is closed, this is called closure. If you will do console.dir(findSum), you can see inside [[scopes]] property, the outerValue is present. It means the inner function has access to the variable outerValue.

jscurious.com

So next time if someone asks you about Closure in JavaScript, you know what to answer.

Thanks for your time☺️
For more Web development blogs, Please visit jscurious.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store