The temporal dead zone or “tdz” for short, is relevant when writing es6 with let and const. Because let and const are block scoped and because they cannot be accessed before they are declared, you can run into situations where let and const are not defined.
Let’s take a look at some examples using our tempura theme:
var favoriteRoll = “Salmon Avocado”; console.log(favoriteRoll);
What do you think will be printed to the console?
“Salmon Avocado” as we expected. Let’s take a look at the outcome when we switch the order.
console.log(favoriteRoll); var favoriteRoll = “Salmon Avocado”;
What will this give us?
It’s not undefined which we got when we used var. We get “Uncaught ReferenceError: favoriteSauce is not defined”.
Why is this happening?
Because unlike var both let and const cannot be accessed before they are declared. MDN provides a good explanation of let and const: “In ECMAScript 2015…. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a ‘temporal dead zone’ from the start of the block until the initialization is processed.”
It’s good to be cognizant of the temporal dead zone when writing code with es6. To help prevent against tdz, it is recommended to declare variables (let / const) at the top of the scope.