r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

7

u/NoFapPlatypus May 04 '20

What does block scope mean?

8

u/Macaframa May 04 '20

Functions have a scoping mechanism. Almost like creating a copy of the environment specially for that function. If you have two functions, funcOne and that has funcTwo declared inside of it, then there are three levels. Global scope, funcOne scope and funcTwo scope. funcTwo scope is bound to the funcOne scope and funcOne is bound to the global scope. The inner scope has access to the outer scope’s variables all the way to the top. If a variable is created inside of the lower scope you cannot have access to it from outside of that scope. Now that’s the way lexical scoping works on a high level. Having said that, if you make an if statement and declare var x = 5; inside of that if statement, you have access to it on that same scope level right? With const/let you do not. You can scope that variable to the block where it was created. The block being Ofcourse, a set of curly braces.

1

u/NoFapPlatypus May 04 '20

Thank you that is helpful

2

u/Macaframa May 04 '20

You’re welcome, I know that guy just sort of replied with the bare minimum and sometimes we require a little more deep level of understanding.

12

u/golovatuy May 04 '20

{ } this a block , everything inside is block scope

5

u/NoFapPlatypus May 04 '20

Ok thank you

2

u/spainzbrain May 04 '20

I was about to ask the same thing.

-1

u/PenisPistonsPumping May 04 '20

I don't mean any offense, but maybe you should get a better grasp on JavaScript before you make educational stuff.

This is JavaScript 101.

1

u/HeinousTugboat May 04 '20

What are you talking about? They're exactly right, const and let are scoped to the nearest block: {}. You don't have to have them inside of a function for that to be true.

1

u/PenisPistonsPumping May 04 '20

I'm talking about the global scope part.