DEV Community

Cover image for let & const in js
Aishanii
Aishanii

Posted on

2 2

let & const in js

We have discussed before that let and const both are hoisted too. But if you try to access a let or const data structure before it's initialized, this is what you get:

console.log(a);
let a=10;
Enter fullscreen mode Exit fullscreen mode

Image description

This error is encountered because a is in temporal dead zone

Temporal Dead Zone

When we declare and initialize data using let and const keywords, unlike var, they are stored in a separate memory space which is not a part of the global space.

So, even though in the first phase of memory allocation, they are hoisted and given value undefined until initialized, they cannot be accessed.

This space between first line of code to execution of code where they are initialized is called the temporal dead zone.

let can be declared in one line and initialized later, but const keyword when used, must be initialized in the same line or throws an error. It is more strict than let.

⭐ var vs let vs const by freecodecamp
⭐ js introduction by interviewbit

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (2)

Collapse
 
badgamerbad profile image
Vipul Dessai • Edited

To be precise the 'temporal dead zone' is the time between accessing a variable and till its 'SCOPE' is created. Therefore try accessing them in a block or a function before initializing, see the magic.

Collapse
 
aishanipach profile image
Aishanii

I took up blocks and block scope in here:
dev.to/aishanipach/block-scope-2g3n

Do check it out and let me know if there is anything that can be improved, thank youu!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more