Facebook Pixel

Why does let x = 1; { console.log(x); let x = 2; } throw ReferenceError in JavaScript?

Because the inner let x is hoisted (shadowing the outer) and is in the TDZ. It does not fall back to the outer x. Accessing it before the inner declaration line throws ReferenceError.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Common Block Scope Bugs in JavaScript

TDZ access: using a let or const variable before its declaration line throws ReferenceError. This is intentional (to catch bugs), so the fix is to declare before use.

Because all cases in a switch share one block scope (unless wrapped in braces). A let in two cases is a re-declaration in the same scope. Fix by wrapping each case in its own block with braces.

Because i++ reassigns i, and const does not allow reassignment. Use let for classic for loop counters. const works in for...of and for...in because each iteration is a fresh binding.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.