0

My question is when i declare a variable of type let or const inside a block like that

//does JS setup a memory space for let a when we are here ? { //or when we are inside the block JS setup the memory space for let a ? let a = 5; } 

will it get hoisted only when we get to the block(at execution time) or will it get hoisted at the beginning ?

because when i call it outside of the block the error is different than the one inside of the block

console.log(a); ---> "Uncaught ReferenceError: a is not defined" { console.log(a); -----> "Uncaught ReferenceError: Cannot access 'a' before initialization" let a = 5; } 

the error outside of the block is the same like a variable that truly doesn't exist

same error

console.log(a); ---> "Uncaught ReferenceError: a is not defined" console.log(thisVariableDoesntExists); ---> "Uncaught ReferenceError: thisVariableDoesntExists is not defined" { let a = 5; } 

so again my question is will Javascript setup a memory space for the variable let a = 5 when we are inside of the block or when the execution context start the creation phase ?

because from what it seems to me javascript will only setup a memory space for let only when we enter the block

DISCLAIMER: if you didn't clearly understood my question DO NOT think that my question was about why when i console.log(a) i don't get the "undefined" like the var but instead i get an error. that is not my question !

Thanks in advance for all the helpers :)

5

1 Answer 1

2

so again my question is will Javascript setup a memory space for the variable let a = 5 when we are inside of the block or when the execution context start the creation phase ?

I honestly don't know the answer to this question, but I wonder ... does it really matter? For any major web application, and likely for most Javascript applications period, it's highly unlikely that you'll even need to think about the the consequences of exactly how much memory your variables use.

Javascript is a garbage collected language, and modern computers are powerful, so the real answer is: make as many variables as you want, in or outside of closures. Make variables even if they're just for code readability, because in a practical sense they have no cost.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.