What are shadowing and illegal shadowing?
Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Both shadowing and illegal shadowing refer to how variable names can "hide" or override others within nested scopes.
Shadowing occurs when a variable declared within a certain scope (like a function or block) has the same name as a variable declared in an outer scope. The inner variable shadows the outer one — meaning, the inner variable takes precedence in its own scope.
Let's take an example where the inner a inside func() shadows the outer variable a.
let a = 10;
function func() {
let a = 20; // Shadows the outer 'a'
console.log(a); // 20
}
func();
console.log(a); // 10
Illegal shadowing in JavaScript refers to a syntax error that happens when you try to declare a block-scoped variable (let or const) with the same name as a variable declared using var in the same or an overlapping scope.
For example, if you declare both block-scoped variable and function scoped variable using the same name inside a function causes an illegal shadowing.
function test() {
var a = 10;
let a = 20; // SyntaxError: Identifier 'a' has already been declared
}
As an another example, if you declare a variable with let or const in an outer scope, and then try to redeclare it with var inside a nested block, JavaScript throws an error — even though var is supposed to be function-scoped. Since the var appears in a block, it ends up trying to overwrite the let in the outer scope, which causes a conflict.
let a = 10;
{
var a = 20; // SyntaxError: Identifier 'a' has already been declared
console.log(a);
}
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.