Facebook Pixel

How do you fix illegal shadowing in JavaScript?

Use let in the inner block instead of var. You cannot shadow a let, const, or class with a var in the same scope because var leaks out of blocks and would conflict. The reverse (shadowing a var with a let) is legal.

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.