DEV Community

Discussion on: Everything is 'undefined' in JavaScript

Collapse
 
valeriavg profile image
Valeria

This is not entirely correct. While the described behaviour is valid for var declarations, modern const and let variables are limited to the scope and cannot be used before their declaration.

Collapse
 
kanhasonu21 profile image
Kanhaiya Kumar

let and const are also hoisted in javascript. If you go deep inside browser you'll see another memory allocation called "Scripts" where these let and const are hoisted.Till the time you didn't put value in let it resides in "Temporal Dead Zone" .
Below link will help more to explain.
stackoverflow.com/questions/331988...

Collapse
 
alimemonzx profile image
alimemonzx

You are completely right.Lets make it easier, at the time of execution let and 'const' variable doesn't register to the global scope. But at the same time they are assigned a value of undefined in their scopes at the creation process. Check the attached image. let b and const c are undefined.
Alt

Collapse
 
valeriavg profile image
Valeria

let and const variables are placed in a Temporal dead zone (TDZ). Hence while they are registered in the program, they are not accessible before initialisation and thus in practice you wouldn't know if they are undefined or not defined at all.

Quote from MDN:

let variables cannot be read/written until they have been fully initialized, which happens when they are declared (if no initial value is specified on declaration, the variable is initialized with a value of undefined). Accessing the variable before the initialization results in a ReferenceError.

This differs from var variables, which will return a value of undefined if they are accessed before they are declared.

Thread Thread
 
alimemonzx profile image
alimemonzx

I never discussed about accessing a variable before or after initialization. That is a separate topic. The thing which I highlighted in this article/blog is every variable is undefined at first and explained the whole process of hoisting,

I appreciate your findings and reference from MDN πŸ‘

Thread Thread
 
valeriavg profile image
Valeria

I left the comment solely because I believe it's a misleading generalisation to say that everything is undefined. I didn't mean in any way to annoy you or offend in any way. I'm sorry of that happened, that wasn't my intention.

Thread Thread
 
alimemonzx profile image
alimemonzx

Well that is why, I explained the title of blog in the post. For better understanding I have use images.

I am not offended at all. I really appreciate you took the time and read article