Facebook Pixel

Why does var return undefined before the line but let throws?

var is initialized to undefined during the memory phase, so it has a usable value. let and const are not initialized until the declaration line, so the gap (TDZ) has no usable value and throws ReferenceError to force declare-before-use.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How let and const Are Hoisted in JavaScript

Yes, memory is allocated for them during the memory allocation phase. But unlike var, they are not initialized to undefined. They sit in the Temporal Dead Zone until the declaration line, and accessing them early throws ReferenceError.

var is hoisted AND initialized to undefined, so it is usable early (returns undefined). let and const are hoisted (memory allocated) but NOT initialized, so they sit in the TDZ and throw ReferenceError if accessed early.

Because an inner let with the same name as an outer variable shadows the outer from the start of the block. If it were not hoisted, the outer would be found. The fact that it throws proves the inner let is hoisted and in the TDZ.

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.