Skip to content

OutputNot attempted

Shadowing let inside a function

let x = 'outer';
function f() {
console.log(x);
let x = 'inner';
}
try {
f();
} catch (e) {
console.log(e.name);
}
console.log(x);

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

The inner let x is hoisted to the top of f and shadows the outer x for the WHOLE function body, so reading it before the let line is a TDZ ReferenceError. The outer x is untouched.