'let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?
Solution 1:
let
is introduced in Ecma Script 6 - the new javascript version - which is still in development at the time of this writing. Therefore, using var
will get you across more browsers for the time being.
On the other hand, I urge people to use let
instead of var
from now on. I would go ahead and list the reasons but you have already have a link in your post with a great explanation in it. Long story short, let
helps you avoid the variable hoisting in javascript and keep your variables' scope at just where it needs to be.
update
I've forgotten about this post until I recently got an upvote. I'd like to update this statement. I personally use const
as much as I can these days. If you get into linting your code, which I highly recommend, and use something like airbnb lint rules, it will also tell you to use const. It will make your variables a constant so you will not be able to mutate them once you set their value thus it is not applicable in all cases. const
and let
also have advantages in terms of scope over var
and it is well worth a read. My hierarchy of usage goes as such const
> let
> var
Solution 2:
Yes, you would want to use let
there as it will be scoped only to that block.
Additionally, using let
in this way will let you avoid accidentally creating a closure if you are calling a function in your loop and passing the counter as a parameter.
EDIT: Maybe this should be better put as: Ask yourself if you need to access the value of your variable outside of the loop. If you do, use var
; in all other cases, use let
.