The first time I heard about the “temporal dead zone” I thought perhaps we had left javascript land and were talking about some type of shrimp tempura. Indeed, I was wrong. I must have been hungry at the time.
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?undefinedSince variables are hoisted in javascript, favoriteRoll’s declaration and not initialization is hoisted to the top of the scope. Check out MDN’s section on var hoisting in case you want to learn more.
Now let’s try our new friends let and const.
let favoriteSauce = “soy sauce”;const WESTCOASTROLL = “California Roll”;console.log(favoriteSauce);console.log(WESTCOASTROLL);
**What will this produce?**“soy sauce”“California Roll” are correct.
Let’s switch up the order.
console.log(favoriteSauce);console.log(WESTCOASTROLL);let favoriteSauce = “soy sauce”;const WESTCOASTROLL = “California Roll”;
What does this produce?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.
Senior, Lead, or Principal developer in NYC? Stride is hiring! Want to level up your tech team? See how we do it! www.stridenyc.com
Originally posted on the Stride Blog. Author: Linda Gonzalez