Why does second have access to variable a?
The answer is B because JavaScript uses lexical scope.
When a function is created inside another function, the inner function can access variables from the outer function where it was defined.
For example:
function first() {
let a = 10;
function second() {
console.log(a);
}
second();
}
Here, a belongs to the outer function first(). The inner function second() can access it because JavaScript looks for variables through the scope chain.
The lookup works like this:
1. Look inside second()
2. If not found, look inside first()
3. If not found, look in the global scope
Since a is found in the outer function's scope, second() can use it.
This is also the basis of a closure. A closure allows an inner function to remember and access variables from its outer lexical environment.
Why the other options are incorrect:
A is not the best answer because a is not declared inside second() itself.
C is incorrect because the prototype chain is used for object property lookup, not local variable scope lookup.
D is incorrect because hoisting explains how declarations are moved during compilation, but it does not explain why an inner function can access an outer function's variable.
Therefore, the verified answer is B.
Currently there are no comments in this discussion, be the first to comment!