JavaScript Hoisting and TDZ: Why var Returns undefined While let Throws Errors
JavaScript engines process code in two phases: a creation phase that registers all variable and function declarations, and an execution phase that runs code line by line. Variables declared with var are registered and initialized to undefined during creation, so accessing them early silently returns undefined rather than throwing an error. In contrast, let, const, and class declarations are registered but left uninitialized, placing them in a Temporal Dead Zone (TDZ) until their declaration line is reached — any early access throws a ReferenceError. Common bugs arise when a var variable is used before its assigned branch executes, or when a function declaration calls a const that is still in the TDZ. Developers can prevent most hoisting-related runtime errors by enabling lint rules such as no-var and no-use-before-define, which catch these issues at write time.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in