What is the Temporal Dead Zone in JavaScript?
Show answer — try answering out loud first
It is the period between the start of the block and the line where a let or const variable is declared. If you try to use the variable during that period, you get a ReferenceError.
The let and const variables are indeed registered (they undergo "hoisting") at the start of the block, just like var. The difference is that they are not initialized until execution reaches their declaration line. That "dead" space, where the variable exists but cannot be used, is the Temporal Dead Zone.
It is actually a safeguard: it prevents you from using a variable before giving it a value, something that with var happened silently (it returned undefined and caused hard-to-find bugs).
// The TDZ goes from the start of the block to the declaration
{
// console.log(mensaje); // ReferenceError: Cannot access 'mensaje' before initialization
let mensaje = "hola";
console.log(mensaje); // "hola" — by this point it has already left the TDZ
}
// Comparison with var (which has no TDZ)
console.log(conVar); // undefined (no error)
var conVar = 1;
// console.log(conLet); // ReferenceError (it does throw an error due to the TDZ)
let conLet = 1;
Confusing the TDZ with "let has no hoisting". It does: the variable is registered at the start of the block. The difference with var is that it is not initialized until its line, which is why it throws an error if you use it beforehand, instead of returning undefined.
"The Temporal Dead Zone is the space between the start of the block and the line where I declare a variable with
letorconst. The variable is already registered, but not initialized, so if I use it beforehand I get a ReferenceError. It is a safeguard: withvar, using the variable ahead of time returnedundefinedsilently, which caused bugs; withletandconst, the error is explicit."
What happens when you run this?
function prueba() {
console.log(valor);
let valor = 10;
}
prueba();
See answer
It throws ReferenceError: Cannot access 'valor' before initialization. The variable valor is in the TDZ until its declaration line, so it cannot be used beforehand.