Should You Truly Never Use var?
First, the arguments against var (the first two adopted from Learn Verified’s new and excellent V3 curriculum).
1. No error is thrown if you declare the same variable twice using var (conversely, both let and const will throw an error if a variable is declared twice)
2. Variables declared with var are not block scoped (although they are function scoped), while with let and const they are. This is important because what’s the point of block scoping if you’re not going to use it. So using var in this context would require a situation in which a variable declared inside a function would need to be used in the global scope. I’m not able to think of any situations where that would be absolutely necessary, but perhaps they exist.
3. Another argument that has been made against the use of var is that JS Linters are now pointing out their use as bad practice. I conducted a quick search on the Internet revealed that Jslint.com and Jshint.com, and did not raise an issues with the use of var as a variable declaration. However, ESLint explicitly has a no-var rule aimed at discouraging the use of var.
“There are going to be places in real world code where some variables are going to be properly scoped to the entire function, and for those variables, var is a better signal”
He provides this code block to illustrate his point:
Essentially, Simpson is arguing that while changing var with let in the example to the left will still work the same, because two blocks explicitly take advantage of let’s block scoping (remember only let/const are block scoped not var), var is a helpful signal to indicate a function scope.
(Simpson also makes the case that when he uses try…catch blocks for debugging, the Let block scope causes unwanted errors.)
Ultimately, after looking at this above example Simpson provides, it’s not difficult to see how var constitutes a cleaner option in that instance.
Of course, many people disagree with Simpson. Sure, in the above example var is a clearer signal than let, but since it operates the same, is it really worth bringing it into play? Also, if his point is that let is a clearer distinction from var, const could work just as effectively at the top of the function scope.