What is Temporal Dead Zone (TDZ)?
TDZ is a term to describe the state of variables where they are not accessible. A variable declared using let
& const
is in TDZ from the start of the block until the initialization has completed.
A variable defined using let
cannot be read/written until they have been full initialized. If no initial value provided, defaults to undefined
.
Whereas, variables declared using the keyword var
will return a value of undefined
if accessed before declaration.
{ //TDZ starts at beginning of scope
console.log(framework); // Returns: undefined
console.log(ranking); // Returns: ReferenceError
var framework = "WebAtoms";
let ranking = "#1"; //TDZ ends here (for ranking)
}
The term "temporal"
is used because the zone depends on the time it is executed (order of execution) rather than position(order) where it is declared.
Q) What will happen if we use typeOf operator on a variable which is in TDZ?
A: It will throw a Reference Error. But when a typeOf
operator is used on a undeclared or undefined variable, no error is thrown.
Have a nice day!
Like | Comment | Save | Share |