Never fear. I have 3 reasons for you to use
Var may be the oldest keyword to declare a variable, but it is by far the only one. It's younger cousins,
const exploded onto the scene with ES6 (over 6 years ago as of this writing!). But if sticking to old norms fraught with perils is your thing, keep using
var and leave these upstart keywords to listen to their terrible pop music and complain about their parents.
for loop or
if block. So a variable declared with
var would be hoisted to the top of its function scope. In other words, the variable declaration moved to the top of the current lexical environment with a value of
undefined. A common issue arising from hoisting is that such variables are accessible outside the block scope, where the developer may not expect them to be.
A subtler and more difficult to detect bug can happen here as well, variable shadowing. Rarely this may be desired. If that is you,
var is your hero.
If you made it this far, you're probably seconds away from pounding out a fierce comment about how I'm wrong about
var. The truth is, no one should be using
const have been available in every major browser for the last 6 years. This is really, really ancient in frontend years.
var isn't just the parent misunderstanding their teen, it's the great grandparent everyone loves but no one invites to the fun parties.
Const creates a -- you guessed it -- constant variable in block-scope.
Const creates a variable that cannot be reassigned, but similar to most other languages,
const objects can have their properties mutated. These two alternatives to
var should cover every use case you have. Even if you are in the tough spot of needing to support truly archaic browsers, don't use
var. Use a tool such as Babel.
So please, please, do not use