Yes, let and const declarations are hoisted, but they are hoisted differently from var declarations.
console.log(b); // undefined
let a = 12;
var b = 28;
We know that we can access "b" even before it is initialized. It does not give an error but instead returns a special value: undefined.
console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization
let a = 12;
var b = 28;
This code gives an error, indicating that the variable can only be accessed after it is initialized.
let a = 12;
console.log(a); // 12
var b = 28;
JavaScript allocates memory for "a" and "b" even before a single line of code is executed. In the case of var(b), it is in the global space, while for let(a), it is in the script scope. The memory assigned to "b" is attached to the global object. Although let and const also have allocated memory, they exist in a separate memory space. This memory space for let and const declarations cannot be accessed before they are initialized.
console.log(a);
let a = 12; //TDZ Ends
var b = 28;
The period from when the let variable is hoisted until it is initialized with a value is called the Temporal Dead Zone. If we try to access a variable inside the Temporal Dead Zone, it results in a ReferenceError. In this code, JavaScript allocates memory for "a" in the script (as undefined) even before execution begins. The variable "a" remains in the Temporal Dead Zone until a value is assigned. Anything before the line (let a = 12) represents the Temporal Dead Zone for "a".
let is stricter than var, and const is even stricter than let.
let a;
a = 11;
console.log(a); // 11 --> We can declare and assign a on different lines.
-------------------------------------------------------------------------
const b;
b = 28;
console.log(b);//Uncaught SyntaxError: Missing initializer in const declaration.(We have to initialize it on the same line.(Like this-->const b = 28))
-------------------------------------------------------------------------
const b = 30;
b = 28;
console.log(b);//script.js:37 Uncaught TypeError: Assignment to constant variable.
Credits to Akshay Saini.
Top comments (0)