What is the temporal dead zone, and which declarations does it apply to?
The temporal dead zone is the short period of time between the moment your code enters a scope and the moment a let, const, or class declaration in that scope actually runs. The name is already reserved during that period, because the engine creates every binding before it starts executing the code, but the binding does not have a value yet. If you read the name during that window, JavaScript throws a ReferenceError.
console.log('start');
try {
console.log(later); // ReferenceError - the name exists but is not ready
} catch (err) {
console.log('caught:', err.name); // 'ReferenceError'
}
let later = 'declared further down';
console.log(later);
The dead zone applies to let, const, and class declarations. It does not apply to var, because a var binding is given its empty value straight away, and it does not apply to function declarations, because the whole function is created before any of your code runs.
The reason the dead zone confuses people is that it turns an ordinary ordering mistake into a crash while the program is running. The code reads as if the variable were simply not there yet, but instead of a blank value you get an exception. The message names the variable instead of telling you plainly that you used it too early. The fix is almost always to move the declaration above its first use, or to restructure the code so that the declaration runs first.
The dead zone also explains a confusing detail about the typeof operator. Using typeof on a name that was never declared at all is safe, and that is the basis of feature detection. Inside the dead zone it still throws, because the binding does exist and the engine refuses to read a binding that has not been initialised yet.