DEV Community

kim-jos
kim-jos

Posted on • Updated on

Is let & const Hoisted in JS?

Is let & const hoisted?

In short, yes. But when a variable is declared using let or const, memory is allocated in a different space and not in the global object like when a variable is declared with var.

console.log(a); // cannot access 'a' before initialization
console.log(b); // undefined
console.log(c); // c is not defined
let a = 1;
var b = 2;
Enter fullscreen mode Exit fullscreen mode

As you can see in the browser screenshot below with a debugger on line 2, JS allocated a value of undefined to variables declared with let in the same way that it does with var. The only difference is that it is stored in a different memory space which prevents it from being accessed before it is initialized. We say that this variable is in the temporal dead zone which we will get into in the following section.

To sum up, let & const is hoisted. But in a different memory space which prevents access before initialization.

image

What is the temporal dead zone in JS?

The temporal dead zone is the time starting from when a variable was hoisted using let or const to the time when that variable is initialized. The following example will hopefully clear up any confusion.

console.log(a); // This console.log(a) is in the temporal dead zone because variable *a* has not been initialized yet. 

let a = 1; // this is when variable *a* is initialized. Anytime before this line is the temporal dead zone.
Enter fullscreen mode Exit fullscreen mode

How do you use const?

Const is abbreviated for constant which means that it should not be changed. But there are some things that can be changed in const which makes it confusing! Let's dive in to see what you can and cannot change. First, you cannot change the value for primitive data types such as numbers, booleans, strings, etc. in const. As you can see in the example below, once you declare a const with a value of 1, you can't change it afterwards. This is the same for reference variables such as objects and arrays. Once an object or array is referred to using const, you can change the properties inside the object but you cannot change the object or array you are referring to.

let a = 1;
a = 3; //this is possible
const b = 1;
b = 3; // this is NOT possible
Enter fullscreen mode Exit fullscreen mode
let a;
a = 3; // this is possible
const a; //this is NOT possible
Enter fullscreen mode Exit fullscreen mode
let a = {name: 'joe', age: 34};
let b = {name: 'kim', age: 30};
const c = a;
c.age = 25; // this is possible because you can change the properties in an object with const
c.school = "Diamond Bar HS" // this is possible. You can add properties as well
c = b; // this is NOT possible because you are changing what you are referring to
Enter fullscreen mode Exit fullscreen mode

Top comments (0)