In JavaScript, the temporal dead zone behavior occurs when a variable declared with a let or const keyword after it has been used. That's means, variable declaration comes later. As a result, it produces a ReferenceError.
In this article I will explain the JavaScript's temporal dead zone behavior in details with example.
Example Illustration
Look at the following sample code where the greetings variable is printed first and then declared with the var keyword. Because of hoisting behavior in JavaScript, this sample code prints undefined value for greetings variable.
console.log(greetings);
var greetings = "hello world";
Output:
-------
undefined
However, if you run the same code by replacing the var keyword with let or const keyword, it will produce ReferenceError.
console.log(greetings);
let greetings = "hello world";
Output:
-------
ReferenceError: greetings is not defined
Why? Why hoisting behaves differently when variable declared with let or const keyword?
In JavaScript, hoisting moves up the variable declaration (but not the variable initialization) to the top of their scope before executing the code. In hoisting, if the variable declared with var keyword then it is initialized with undefined value by default. But this default undefined value is not assigned to the variable if declared with let or const keyword, and hence produces ReferenceError. This is called temporal dead zone behavior in JavaScript which occurs when a variable declared with a let or const keyword after it has been used.
Summary
In a nutshell, a variable declared with let or const keyword do hoist but don't get initialized and hence produced ReferenceError. To avoid this temporal dead zone behavior, you should always declare and initialize variables at the top of their scope when declared with let or const keyword.
Happy JavaScript coding!
Comments
You are welcome to write comments, suggestions, corrections, or any queries related to the article. Your comments may take some time to be appeared. Please be aware that any irrelevant comments will be deleted. Thanks for your understanding, and your respectful & relevant comments!