CodeZettaInterview Hub

JavaScript · Scope · Senior · Concept

Explain illegal shadowing and how `catch` clause bindings interact with block scope.

Short Interview Answer

You cannot shadow a `let`/`const` with `var` in nested blocks of the same function in ways the spec forbids; `catch` bindings are block-scoped to the catch block.

Detailed Explanation

Shadowing is normally allowed (`let x` inside a block can hide outer `let x`). Illegal shadowing occurs in specific cases — notably declaring a `var` that would hoist across a block containing a `let`/`const` of the same name, or conflicts between function-scoped and block-scoped names that the early error rules catch at parse time. A `catch (err)` parameter is scoped only to that `catch` block (like `let`). Optional catch binding (`catch {`) avoids an unused binding. In nested try/catch, each `err` is independent. These rules matter when transpiling or when debugging surprising SyntaxErrors about redeclaration.

Example

try {
  throw new Error('boom');
} catch (err) {
  console.log(err.message);
}
// console.log(err); // ReferenceError outside catch

Interview Tip

If asked for depth, mention optional catch binding and that `err` is not like a `var`.

Common Mistake

Treating `catch (e)` as function-scoped like an old `var`.

Did you know this answer?