JavaScript Easy technical 1 views 2 min read

What are shadowing and illegal shadowing?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of JavaScript conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?