Const Is the New Var
We hear a lot of praise recently about the introduction of new cool features in ES6. One of those long awaited ones is the let
keyword. And rightly so - it has saner scoping rules, does not hoist (I know, I know but let's ignore TDZs here) and generally does not “pollute” your function’s namespace as much as var
. Truth be told there’s really not much reason to use var
anymore.
But ES6 brings about yet another great feature which should get more attention: the const
keyword. const
is an immutable reference - that essentially means you can change the value but you cannot reassign the variable.
Now, this may not sound like much but, well, it is a subtle yet big win. Think about it - we can now flag our variables as const
to signal that they’re not to be changed and the system - usually a transpiler such as babel - guarantees that (up to a certain level).
Obviously, this is not as strong as full immutability so we can still only silently envy languages that were actually designed (I'm looking at you, clojure). But it still prevents a number of annoying bugs and most importantly, it’s a hint that helps us understand what happens to data within a function!
Consider the following snippet:
function iUseConstVars() {
const path = '/foo/bar';
const val = 'value';
const myObject = {some: 'object'};
let result = {first: 'value'};
// lots of SLOCs
result.second = 'value';
return result;
}
Just glancing at the function body, you get a strong visual (and a weaker "functional") clue about which data is constant and which is mutable - and hence you should invest time to understand how it changes. And considering code is WORM any clue we can give to the readers is certainly more than welcome.
Sadly, there is no way in ES6 to ensure full immutability for data structures at syntax level (although there's seamless-immutable if you don't mind the extra (mental) overhead). But const
is definitely a snippet of a better future.
TL;DR
Every time you declare a variable using let
, have a think about whether you didn't in fact mean const
. And if you did, please use const
instead. You'll make your future self a happier person.