CodeNewbie Community

John Pouliot
John Pouliot

Posted on

Why shouldn't I use "var" in JavaScript?

Discussion (3)

Collapse
isaacdlyman profile image
Isaac Lyman

You can and should use var in many situations! If you're writing code that will need to run on older browsers (i.e. any code that isn't being transformed by a tool like Babel), var is the only available keyword for variable declaration. You should declare your variables. Although JavaScript doesn't require you to do so, declaring your variables helps you avoid mistakes like accidentally overwriting a variable from an outer scope, or creating a variable at a higher scope than you intended.

In newer versions of JavaScript you have access to let and const. These are nicer than var for a few reasons. For one, they're block-scoped instead of function-scoped, so it's easier to see where you're allowed to use the variable; in most cases just look for the nearest curly braces { before and after the declaration }. For another, they help you tell everyone what your plans are for the variable. If you don't want the variable to change, use const (remember that if the variable points to an object, you can still update the object's properties, add and remove properties, etc.--and if it points to an array, you can add, remove and change items in the array as well--just so long as you don't try to point it to a different object or array). In most cases, you'll use const. If you plan to overwrite the variable, use let.

There's absolutely nothing wrong with var, and we used it just fine for years. So if your project uses var, don't sweat it. But if you have the option to use let and const instead, that's a great way to make your intentions a little more clear. And making your intentions clear is the secret to good code.

Collapse
ben profile image
Ben Halpern

Great answer!

Collapse
weswedding profile image
Weston Wedding

As Isaac touched on, it can be easier to understand and reason through code that uses let and not var, which I consider to be one of the most important aspects of writing code. JavaScript's Hoisting is very unintuitive to many people!

There can also be specific circumstances where let and var have performance differences in some Browsers and maybe even some versions of NodeJS. However, this level of min/maxing your coding is not something you should worrying about unless you are writing a complex library that needs to a lot of heavy, repetitive tasks like processing large quantities of images or handling a high bitrate datastream from a stock exchange. Some early browser implementations of let and const were signficantly slower than var, but those were bugs that got fixed.