CodeZettaInterview Hub

JavaScript · Hoisting · Mid-Level · Code Output

What is logged and why? ```js console.log(a); console.log(b); var a = 1; let b = 2; ```

Short Interview Answer

First log prints `undefined`; second throws ReferenceError due to TDZ on `b`.

Detailed Explanation

`var a` is created and initialized to `undefined` during the creation phase, so reading `a` before assignment yields `undefined`. `let b` is also created during creation but remains uninitialized until the `let b = 2` line executes, so accessing `b` earlier is a TDZ ReferenceError. The first `console.log` does run; the second statement throws and stops further execution.

Example

console.log(a);
console.log(b);
var a = 1;
let b = 2;
// undefined
// ReferenceError: Cannot access 'b' before initialization

Interview Tip

Walk creation phase then execution phase out loud.

Common Mistake

Saying both throw, or both log `undefined`.

Did you know this answer?