TLDR Take Away
Method-1
(easy to practice) Always use let
!
Method-2
(most agreed in community) Use const
by default, only change const
to let
if afterwards you find yourself in need to change/update the variable.
TLDR Comparison
var
- Declares a variable with function-scope or globally if declared outside of a function.
- It can be re-declared and can be updated.
let
- Declares a variable with block scope (i.e., confined to the block, statement, or expression where it is used)
- It cannot be re-declared within the same scope, but can be updated.
const
- Similar to let in terms of block scope
- The variables declared with const must be initialized at declaration,
- Const varaibels cannot be updated, and cannot be re-declared.
(If you are really into knowing the fine difference between each keyword, there’s plenty materials you can find online, I’ve put some of the MDN official documents in the reference section for reference purpose.)
Potential Issue with var
For the following code you might be anticipating the output to be strings of every wizard
in wizards
appearing twice, but actually it is only doing output for the wizards
interleaved with last item of items
.
|
|
|
|
Why is that?
- This is because var is globally scoped (or functionally scoped), every iteration after we first declare it in in
line 4
(as some item of thewizards
array), it will get redeclared and overriden atline 6
; And since it is not block scoped, when it leaves thefor
block atline 8
it will never get poped back to the value it once was before entering the block, hence when we arrive atline 9
it will always be the last item of theitems
array