JavaScript · The language round
What is the scope chain in JavaScript?
Short answer
JavaScript resolves variables lexically. An inner scope can read bindings from its outer scopes, but an outer scope cannot read bindings declared inside an inner scope.
Every function and block creates a scope. When code reads a variable, the engine looks in the current scope first, then walks outward through the chain of enclosing scopes until it finds the binding or reaches the global scope. That lookup path is fixed when the code is written, not when it is called.
const appName = "VocalHyre";
function outer() {
const topic = "closures";
function inner() {
const detail = "lexical";
console.log(appName, topic, detail);
}
inner();
console.log(detail); // ReferenceError
}
outer();inner can read topic and appName. outer cannot read detail.Lexical, not dynamic
Lexical scoping means the call site does not decide which variables are visible. A function called from another file still sees the scope where it was defined. That is also why closures can keep private state alive after the outer function returns.
The scopes you will meet
- Global or module scope: top-level bindings
- Function scope: parameters and
vardeclarations - Block scope:
let,const,classand function declarations inside a block - Catch scope: the error binding in
catch (error)
Shadowing happens when an inner declaration uses the same name as an outer one. The inner binding wins for the rest of that block, but the outer binding is unchanged.
let count = 1;
function increment() {
let count = 2;
count += 1;
return count;
}
console.log(increment()); // 3
console.log(count); // 1var declaration inside a block is function-scoped, so it does not create a block-level binding. let and const do.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between lexical and dynamic scoping?
- 2What happens when two scopes declare the same variable name?
- 3How does the scope chain make closures possible?
- 4Does a `var` declaration inside a block create a new scope?
Say it in the interview
JavaScript uses lexical scoping. When code reads a variable, the engine checks the current scope, then the enclosing scopes, then the global or module scope. That chain is determined by where the function is written, not where it is called. Inner scopes can access outer bindings, but outer scopes cannot access inner ones. Shadowing lets an inner binding reuse a name without changing the outer one.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.