Hoisting with var, let and const in Javascript
Mohammad Inshal P
Angular Developer || Software Developer Associate @LRN || Ex-Capgemini
Hi All,
I wanted to write one of my first article on a fundamental yet important topic in JavaScript: Hoisting.
I know most of you are already familiar with the basics of hoisting, but during a deeper dive into JavaScript, I came across an interesting concept: the Temporal Dead Zone (TDZ).
So, what is the Temporal Dead Zone, and how is it related to hoisting in JavaScript?
Let’s start with the definition of hoisting.
Hoisting:
Hoisting is a concept where variable declarations are moved to the top of their scope before code execution begins.
Simple, right?
But now, let’s look at two pieces of code and predict their output:
Code 1:
console.log(x);
var x = 1;
Code 2:
console.log(y);
let y = 2;
Or?
领英推荐
console.log(z);
const z = 2;
At first glance, you might expect the output to be the same for both. But after executing the code, you’ll notice a difference.
? For Code 1, the output will be undefined.
? For Code 2, the output will be a ReferenceError.
This difference arises because var, let, and const behave differently when hoisted.
The Reason:
? For var: Variables declared with var are hoisted and initialized with undefined. (This is the usual behaviour.)
? For let & const: Variables declared with let and const are also hoisted, but they are placed in the TDZ (Temporal Dead Zone). If you try to access them before they are initialized, you’ll encounter a ReferenceError.
Now, let’s explain what TDZ is.
TDZ (Temporal Dead Zone):
The Temporal Dead Zone is a concept in JavaScript that occurs when using let and const variables. If a variable is hoisted but not yet initialized, it exists in the TDZ. This means any attempt to access the variable during this period will lead to a ReferenceError.
Keep learning, and your feedback is always appreciated!