Closures and Lexical Scoping in JavaScript
Amitav Mishra
Posted on November 14, 2020
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.
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.
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
. 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.
You may also like
- 20 JavaScript Shorthand Techniques that will save your time
- What are call(), apply() and bind() in JavaScript
- What is ES6 Destructuring Assignment in JavaScript
Thanks for your time
Find more Web dev blogs on jscurious.com
Posted on November 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
July 16, 2022