JavaScript Interview Question #7
What is lexical scope in JavaScript?
JavaScript Fundamentals, Types, Scope & Functions Junior Beginner
Quick Interview Answer
Lexical scope means that variable accessibility is determined by where functions and blocks are written in the source code. An inner function can access variables from its own scope and from its enclosing scopes.
Detailed Explanation
Lexical scope means that variable accessibility is determined by where functions and blocks are written in the source code. An inner function can access variables from its own scope and from its enclosing scopes.
JavaScript resolves identifiers through the lexical scope chain. This behavior is fundamental to closures because a nested function can continue to access variables from the environment in which it was created.
Code Example
const appName = "My App";
function outer() {
const user = "Asif";
function inner() {
console.log(appName);
console.log(user);
}
inner();
}
outer();