ES6 brings a lot of great features to the JavaScript language, and one of those is constants. Constants sound simple enough, eh?
Well, many JS developers misunderstand them so… let’s walk through the feature (and more)!
Constant? Constant what?
Good question! In JavaScript, constants are constant in reference.
Reference? Reference to what?
A reference to a value.
‘hi’, 5, [], {} // all values
However, it’s important to note that in the case of objects (and thus, arrays), the value is a reference to the object itself.
So I just can’t change the value of a “constant”?
Sorta.
This calls for a quick lesson on types in JS. There are five primitive types: undefined, null, boolean, string, and number. Everything else is an object. Values, not variables, are first-class. And, as I mentioned earlier, the value of an object is merely a reference. By design (long before ES6), all primitives are immutable, and objects are mutable.
Thus, when you “change” (at least, as it seems) the value of an immutable (i.e. ++), you’re not actually mutating but instead re-assigning it to an entirely new reference since assignment is merely the process of creating said “reference”.
const num = 2;num++; // TypeError// ++ is just short-hand for +=, clearly assignment
Yet, since objects are mutable, you can change their value with or without re-assignment.
const arr = [1, 2];arr.push(3); // [1, 2, 3]arr = [1, 2]; // SyntaxError (thus, value != reference)
And, only re-assignment- is blocked by ES6 _const_ants since it deals with references, not values.
What’s the benefit?
Constants primarily benefit readability but may eventually benefit performance as well. If you know a value won’t be replaced, you may know more about the intent of the program.
Rule of thumb- use const unless you need re-assignment — in which case, you should most likely use let to still reap the benefit of block-scope, but we’ll save that for another post.
Use constants to step up code readability with minimal effort, but first, make sure you understand them! Just my 2¢.
If you found this interesting, consider following me on Twitter and GitHub, where I share cool code and more.
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!