Let vs Const vs Var in ES6

In my mind, one of the best additions to EcmaScript 6 over previous versions is the inclusion of Let and Const keywords to use when defining variables, as opposed to the old Var keyword. The Var keyword still exists in ES6, which has led to a debate about which is better, or when to use each keyword. For any readers not familiar with the difference between these three, I’ll outline them here.

Var

The Var keyword, as you’d expect defines a variable. This variable is given “function scope.” When I first started studying JavaScript, before ES6 was released, this gave me headaches to no end. Out of the 16 different programming languages I know, JavaScript is the only one I’ve encountered that uses this “function scope.”

Let

The Let keyword, new to ES6, is very similar to Var, with one key difference. Variables defined with Let are given “block scope.” Block scope, being very common among programming languages, makes it much easier for experienced developers to use.

Const

Rather self-explanatory for experienced developers, the Const keyword defines a constant. Don’t ask me why the core JavaScript team waited this long to add constants to their language, or how the devs dealt with that.

The Debate

Now that I’ve outlined the difference between the two, we get to the debate. Should you still use Var? Should Const be restricted to proper constants, or should it be your default?

For starters, I looked at a blog by Mathias Bynens. He suggests that Var should be forgotten about when writing ES6. Personally, I’m inclined to agree. As I noted above, the function scope that Var gives is very unusual in the programming world, and caused me a great deal of headaches.

Now, Mathias also says that your default should be Const, and that you should only use Let when you know that you’ll change the value. He also refers to the idea that “Const is for constants” is a misunderstanding.

This is where I disagree. It should be fairly obvious that Const is short for constant, and thus, it should be treated as such. In my research, I came across a website that compares runtime performance of code when using Var, Let or Const. Running these tests numerous times, I have not seen any performance advantage in using one over the others. So I see no particular reason to default to using constants for everything.

What I suggest is this. Unless you are absolutely certain that the variable you’re declaring will not change values, I suggest using Let. That way, if you find a point that you need to change the value, you won’t have to go hunting for that declaration. After all, they’re called “variables” for a reason.

Advertisements