Justin Chmura

Don’t Use var Anymore

By on

As the web transitions to ES6, developers will need to break their habit of using var. The toolbox now contains const and let, which should replace var in all instances.

Now that that’s out there, the real question now is which to use when? TL,DR: always use const, unless it’s a native value (number, string, null, etc.) that could change, then use let.

The Case Against var

All JavaScript developers run into the issues with var from time to time. Majority of the time it stems from scope and hoisting, which is different from a lot of other languages.

Hoisting is one of those common JavaScript gotchas which confuses developers. let can get rid of this confusion and even help with scoping bugs. More on this later.

Almost Always: const

Why? Well the first thing to note is const in JavaScript isn’t a real constant. Think of it more as a pointer (in reference to C++) that doesn’t move. This doesn’t make things immutable, just that its memory location cannot change. Do note, this does allow an object’s properties to be modified, just can’t assign the variable to a new value.

Some have said that it obscures the code’s intent and can be confusing when compared to other languages. This is understandable but a counter could be var is just as confusing to new developers due to scope.

Sometimes: let

This one is the exception to the rule. There’s always values that will change, and when a primitive does, use let. Then why is it better than var since let sounds like the same thing?

The answer is because of block scope. var has function scope, whereas let has block scope or within curly braces. As I mentioned earlier, this cuts confusion and keeps the code from stepping on itself. This emulates the behavior of other popular languages.

Stop Using var

Due to some browsers being slow to put ES6 features in place, dropping the var habit may take some time. Node has these baked in, so go ahead and start implementing them there. This will not only make the code future-proof, but make it easier to understand. So my advice, don’t use var anymore.