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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var wizards =  ['Merlin',    'Gandalf', ..., "Ursula"  ]; 
var items   =  ['Spellbook', 'Staff',   ..., "Urchins" ]; 

for (var item of wizards) {
	console. log(1, item);
	for (var item of items) {
		// Stuff happens...
	}
	console.log(2, item);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Expected Output: 
	1 Merlin
	2 Merlin
	1 Gandalf
	2 Gandalf
	1 ...
	2 ...
	1 Ursula
	2 Ursula

# Actual Output: 
    1 Merlin
	2 Urchins
	1 Gandalf
	2 Urchins
	1 ...
	2 ...
	1 Ursula
	2 Urchins

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 the wizards array), it will get redeclared and overriden at line 6; And since it is not block scoped, when it leaves the for block at line 8 it will never get poped back to the value it once was before entering the block, hence when we arrive at line 9 it will always be the last item of the items array

Reference