Temporal Deadzones in JS
Definition of Temporal Deadzone/TDZ
A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value
In simpler terms, TDZ is that area where you will get a "Referance Error" while trying to access a variable that hasn't been initialised yet
TDZ differs for block scope variables(var) and global variables(var)
Lets see below how TDZ behaves difference for each of these variables
1)Variables declared using var
console.log(a)
let b = 10
let c = 20
var a = 40
Output : Undefined
Explanation : Even though variable 'a' is not declared and assigned to any value before the console.log(), variable 'a' gets added to the Global Scope chain in the memory allocation process before execution. This means that at line number 1, variable 'a' does exist in the Global Scope chain but it doesn't have any value assigned to it yet, hence we see undefined
In general the TDZ of var is the following
// tdz starts and ends here
// tdz does not exist here
// tdz does not exist here
// tdz does not exist here
var a = 20
// tdz does not exist here
// tdz does not exist here
2)TDZ of let and const
console.log(a)
let a = 20
console.log(b)
const b = 10
Output for both : Reference Error
Explanation : Although, let and const are also hoisted like var, but they are not assigned any initial value during the memory allocation phase, hence we get a reference error
TDZ of let and const
{
// TDZ of block started
// TDZ of block started
// TDZ of block started
// TDZ of block started
let a = 10 //TDZ ends here
//No TDZ
//No TDZ
//No TDZ
}
{
// TDZ of block started
// TDZ of block started
// TDZ of block started
// TDZ of block started
const a = 10 //TDZ ends here
//No TDZ
//No TDZ
//No TDZ
}
Hope this helps you in understanding the concept of TDZ in JS. Please let me know in case of any error in my explanation Looking forward to your feedback
Thanks