Member-only story
Lexical scope in Javascript — Closures
A lexical scope in javascript is the ability of the inner function to access the variables defined in the outer function.
At the same time, the variables defined in inner function cannot be accessed from outer function.
function outer(lastName) {
return function inner(firstName) {
return `${firstName} ${lastName}`;
};
}
const handler = outer('Thangavel');
console.log(handler('Vinodh')); // Vinodh Thangavel
console.log(handler('Sudha')); // Sudha Thangavel
As you can lastName
which is an argument of parent outer
function, can be accessed inside inner
function.
const handler = outer(‘Thangavel’);
— we are sending the lastName to outer function, returned inner function is assigned to handler.
handler(‘Vinodh’)
— Even though we call the inner function, it has the ability to access the parent scope, that is called lexical scope
in javascript.
function outer(lastName) {
console.log(firstName) //X will result in error, we cannot access inner scope
return function inner(firstName) {
return `${firstName} ${lastName}`;
};
}
const handler = outer('Thangavel');
console.log(handler('Vinodh')); // Vinodh Thangavel
console.log(handler('Sudha')); // Sudha Thangavel