r/learnjavascript • u/Significant-Royal-86 • Apr 19 '26
About block scoped vs function scoped
so from what I understand , when you want to declare variables, you can do that either using let or var, var is like the old method and it got replaced with let and we also use const.
var is function scoped while let is block scoped, and block scoped means that the variable known only inside of the block where you've declared it, inside of curly braces or squiggly brackets. I was watching a video explaining the differences between the three and they used an example using a for loop, and what they did was they used let obviously to declare the i inside of the loop, and when they tried to access it it gave them an error, the interesting part tho isn't that, it's the fact that even after they've deleted the curly braces it still was an error, so like a block then is everything inside of a pair of braces but the loops themselves and conditionals are considered blocks ?
View all comments
Show parent comment
1
u/senocular Apr 20 '26
There isn't just one outer scope ;) Each iteration has its own outer scope. This outer scope is also where the
ilives, its not in the user-defined block ({...}). You can tell if you try and declare a newiin that block. There's no conflict and the loop doesn't try to use thatias part of the iteration.This ends up looking something like
Additional scopes are also potentially created at the start of the loop where set up happens, and again after the last iteration of the loop where the last
iis created that fails the condition. That scope would have been the next iterations wrapping scope if the loop had not ended.