JavaScript Coding Style – Prefer `const` Over `let` for Readability

coding-stylejavascripttypescript

ES2015 introduced the let and const keywords, which essentially have the same semantics apart from reassignment. (const can be seen as a final variable in languages like Java.)

I see the point of switching from var to let, but many online articles recommend using const whenever possible (in some form of manual SSA).

However, I recall in the question on Java final variables, the accepted most popular answer adviced against using final local variables because it makes the code more difficult to understand.

This is reflected in reality as a number of code review comments questioned the "over-use" of const on local variables.

So does const still reduces readability in JavaScript?

Best Answer

*sigh*... This is why immutable needs to be the default. Even the referenced Java answer suggests this. Note that that answer does not recommend removing final modifiers, just that the author of that answer wouldn't add them in new code (for local variables) because they "clutter up" the code.

However, there is a difference between JavaScript and Java here. In Java, final is an additional modifier on a variable declaration, so you get:

final int foo = 3; // versus
int foo = 3;

In JavaScript, though, const is just an alternate variable declaration, so the situation is:

var foo = 3; // (or let nowadays) versus
const foo = 3;

I don't think two more characters constitutes "clutter". If the alternative being suggested is just foo = 3 then the reviewers are just wrong.

Personally, I would always use const when applicable and would suggest it's inclusion in a code review. But then I'm a Haskeller, so I would be like that. But also, JavaScript tends to be more pervasively mutable and have a worse debugging story when things do unexpectedly change, that I would say const in JavaScript is more valuable than final in Java (though it's still valuable there.)

As Ixrec points out, const only controls the modifiability of the binding, not the object that is bound. So it's perfectly legal to write:

const foo = { bar: 3 };
foo.bar = 5;

This can be used as an argument against using const as someone may be surprised when an "unmodifiable" object is modified. Newer versions of JavaScript do have a mechanism to actually make objects unmodifiable, namely Object.freeze. It makes a good addition to const (though only use it on objects that you create, for example, as Object.freeze({ ... })). This combination will communicate and enforce your intent. If used consistently, the times where you are mutating things will stick out and clearly signal non-trivial data flow.