Lately, I've been posting a bunch of really fun content in a series called Mastering Unit Testing on Twitter. The latest tweet is here on the difference between DAMP and DRY in unit testing.
Please go give it a look and like/retweet.
Const is a Lie in JavaScript
The const keyword in JavaScript is a lie and a waste. I recently tweeted about how const is a waste and had a lot of interesting discussions.
But here's the thing about const in JavaScript: it ONLY makes sure that the reference isn't reassigned. But when you use a keyword like const, it implies to you that the thing you're creating is constant, and will remain unchanged throughout the life of the reference. But that's not true. That's not what const does. Even with the best IDE's of today, nothing about this changes.
So this is totally valid:
In JavaScript, we use variables that point at primitives sometimes, but we very frequently point at objects/classes that hold multiple pieces of related data. Even if we use const, this data can be changed at will as above.
Ultimately, const is a little better than a comment when you declare a variable.
So there are two ways to improve this. First, follow the long time tradition of making constants all uppercase.
The second and even cooler way is to use the Readonly type in TypeScript. Thanks to Val Neekman for this sample:
And now, you get REAL constants, not half ones…
Happy Coding!
Signup for my newsletter here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster
Top comments (8)
There are two separate concepts:
You can have immutable values assigned to not referentially transparent variables, for example:
I think we can achieve the same in javacript using
const todo = Object.freeze({title: 'js is awesome'})
I think this method is much more standard and it's used much more widely. freeze and seal are a must know.
Keep in mind it is not recursive. See github.com/substack/deep-freeze
This article:
const
doesn't mean constant value; if you think it means constant value, then you can blameconst
and call it a lie.Lies in this article:
const
implies constant value (narrator: it's not; but it can be very confusing)const
(narrator: it can, especially when using TypeScript, or other sound type systems; eslint also has rules for this)const is Java's final, not C's const - final has its uses, of course, but I do wish they'd used the right name.
It is true. The reference (pointer) cannot be reassigned. The object that is being referenced/pointed to can still be modified. In C++, this is the equivalent of a constant pointer to a non-constant object.
Thanks, this was an interesting read. 😁