3

ECMAScript 6 introduced let and const keywords for variable declaration.

That being said, is there any reason to use var to declare a variable?

vinibrsl
  • 6,563
  • 4
  • 31
  • 44

2 Answers2

4

Backwards compatibility (writing/maintaining ES5) or the ability to write/maintain sloppy code.

var, unlike let or const can redefine a variable multiple times in the same scope. Particularly if you are refactoring something that was already a mess, you might need to stick with var for a little while.

There is plenty of code out there that redefines i in multiple for loops, which would throw an error if you replace one instance with let.

This is something that linting tools have been able to catch for years, but that doesn't mean all the sketchy code out there went away.

Sam R
  • 696
  • 3
  • 7
2

The main reason is backwards compatibility. Other than that, not that I can see. So if you are using a transpiler then really no point in using var. Unless you need a global variable but that is evil.

nathan hayfield
  • 2,627
  • 1
  • 17
  • 28
  • Also against, it, but I recommend writing `window.myVar` if you need a global. It's harder to miss that way. – Sam R Sep 08 '17 at 00:03
  • 1
    @SamR Not everyone uses JS in the browser, and even there there's not always a `window`. – Bergi Sep 08 '17 at 00:09
  • @Bergi That's true. I tend to focus on client-side. You can create a global with `let` in any environment, so even then you don't need `var`. – Sam R Sep 08 '17 at 00:13
  • 3
    @SamR A problem with that is that [`let`/`const` variables cannot be declared multiple times](https://stackoverflow.com/q/36140252/1048572), which is often desirable for global variables. – Bergi Sep 08 '17 at 00:23