javascripting
javascripting

Reputation: 1153

javascript LET variable - why getting undefined and not error when logging before initializing variable?

I know there are many many posts on const/let but I couldn't find anything that answered my question:

To my knowledge variables declared using let, are being hoisted to the top but not initialized with undefined like with var, so they create a temporal dead zone until initialized.

In the example below, I log undefined. Why is it undefined if my console log comes before initialization and why don't I see a reference error?

let x;
console.log("x: ", x)
x = 1;

//without x= 1 it would be undefined too

EDIT

let x; 
console.log("x: ", x) 

will be READ eventually EXACTLY SAME AS

console.log("x: ", x); 
let x = 1

Upvotes: -1

Views: 3978

Answers (4)

SourabH-0156
SourabH-0156

Reputation: 1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz

While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a ReferenceError. The variable is initialized with a value when execution reaches the place in the code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of undefined.

Upvotes: 0

uzumaki
uzumaki

Reputation: 1

you actually are in the temporal dead zone. temporal dead zone for a is the time period between the a is hoisted and it been initialized. so when you console.log(a) it is in the temporal dead zone

Upvotes: -1

James
James

Reputation: 176

"let x" declares a variable but hasn't assigned it a value yet. According to Mozilla's JavaScript docs - "A variable that has not been assigned a value is of type undefined." hence the value of 'x' before it has been assigned a value is 'undefined'. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#Description

Upvotes: 1

Pointy
Pointy

Reputation: 413737

That description of hoisting and the dead zone is about a different situation:

console.log("x: ", x);
let x = 1;

That's treated as if the let x; appeared at the top. However, the console.log() in this case would give an error, because it appears between the "virtual" position of the declaration and the initializer.

In your case, the let x; has no initializer, so x can be used anywhere after the declaration. And there's nothing special about the x = 1 statement; it's just another reference (well, an assignment) to x.

Upvotes: 1

Related Questions