1. Lexical Scope / Scope Chain
The ability of JavaScript engine to search for a variable in the outer scope when variable is not available in local scope is known as
lexical scope or scope chain.
It is ability of child to access variable from outside if its not present in local scope
2. Lexical Scope: A function and global object
let a = 10;
function test() {
a++;
console.log(a);
}
test();
// Output: 11
When test function is executed js engine looks for 'a' in local scope. Since it will not available it will look for a in outer scope that is global window object.
3. Lexical Scope: Child function and parent function with closure
function outer() {
let a = 10;
function inner() {
console.log(a);
}
return inner;
}
let res = outer();
res();
// Output: 10
When the function inner is executed and console.log(a) is encountered, js engine looks for a in the local scope of function inner.
Since, a is not present and function inner is child of function outer js engine will search for a in the parent function outer scope with the help of closure.