Published in

Const Is A Lie In JavaScript & Mastering Unit Testing

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: | Facebook: @gothinkster | Twitter: @GoThinkster



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joe Eames

Joe Eames

Mormon, Christian, Father, CEO of, Organizer of @ngconf, @frameworksummit, React Conf. Front end developer, and Software Craftsmanship Evangelist.