Diagnose ReferenceError failures
Reviewing code that reads a const before its declaration
JS Puzzles · Const
The temporal dead zone is the interval from entering a block until execution initializes a let, const, or class binding. Accessing the binding during that interval throws a ReferenceError.
A const binding exists throughout its block, but it remains uninitialized from block entry until execution reaches its declaration. Accessing it during that interval throws a ReferenceError; the relevant boundary is execution order, not merely the declaration’s position in the source.
const identifier = initializer;typeof does not safely probe a lexical binding while it is in the temporal dead zone.{
console.log(value); // ReferenceError
const value = 42;
}The access happens before initialization, so execution throws instead of producing a value.
Reviewing code that reads a const before its declaration
Explaining why declaration order and call order can differ
Auditing early typeof checks for lexical variables
A const binding is in the TDZ from the beginning of its block until execution reaches its declaration and initialization. Reading it earlier throws a ReferenceError rather than returning undefined.
Follow-up: Does moving the declaration text always fix the problem? No: the access must execute after initialization, so control flow and calls matter.
The TDZ is based on execution order. A function may be defined before a const declaration and still read that binding successfully when called after the declaration has executed.
Follow-up: What happens if the function is called before initialization? Its read occurs inside the TDZ and throws a ReferenceError.
var is initialized to undefined during hoisting, whereas const remains uninitialized until its declaration executes. Consequently, an early const access throws a ReferenceError.
Follow-up: Does typeof avoid this error? No; applying it to a lexical binding in the TDZ also throws a ReferenceError.
letvarconst declarationsblock scopeReferenceError