That escalated quickly!
An earlier post describes how ECMAScript 2015 has introduced a new way to declare variables: let
. A variable declared with let
uses block scope instead of function scope.
ES2015 didn’t stop there, though. It also introduced another way to declare variables: const
.
If you’re a programmer with a history in C/C++/C#/Java, the notion of a constant is probably familiar: A variable with a read-only value, a value that may not change.
Here’s a simple JavaScript const
example:
const derp = 'foo';
derp = 'bar'; // causes an error
(The error I see in the Chrome console as I test drive this code: Uncaught TypeError: Assignment to constant variable.
Nicely straightforward.)
Constants in typed, compiled languages are assigned at compile time. JS isn’t compiled, it’s interpreted. So const
is a little different than we’re maybe used to. The value in a const
doesn’t have to be known at compile time. It can be something dynamic. It just can’t change once it’s set.
function addDerp(target) {
return target + ' derp';
}
function foo(target) {
const result = addDerp(target);
return result;
}
console.log(foo('herp')); // works fine, prints 'herp derp'
Another thing to know about const
: If you use it to declare an object or array, you can still perform operations on your variable without errors. You just can’t totally reassign to the variable.
With an object:
const obj = {
firstName: 'Joe',
lastName: 'Schmoe'
};
obj.firstName = 'Moe'; // works fine, assigns new value
obj = {}; // causes error
With an array:
const array = [];
array.push('it real good'); // works fine, pushes string onto array
array = []; // causes error
If you’re wondering: const
uses block scope, like let
.
Alright, so we’ve covered the what. Now to the why. To my mind, const
is useful for two main reasons.
-
When the code says a value cannot change, we get to rule out the possibility of that value changing. This gives our brains a little break. Lots of little breaks like that add up.
-
When you can tell your compiler or interpreter that a value will not change, there are things it can do to optimize your code’s performance. (Disclaimer: I take this claim on faith a little bit. I don’t know much about the specifics of those optimizations.)
I’ve seen it suggested that const
should be your default, let
should be used only where you really can’t use const
, and var
should be used virtually never. I like the sound of that, but don’t feel strongly about it. (Yet?)