Const Is A Lie In JavaScript & Mastering Unit Testing

Joe Eames
Joe Eames
Dec 3, 2020 · 2 min read
Image for post
Image for post

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:

Image for post
Image for post

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.

Image for post
Image for post

The second and even cooler way is to use the Readonly type in TypeScript. Thanks to Val Neekman for this sample:

Image for post
Image for post

And now, you get REAL constants, not half ones…

Happy Coding!

Signup for my newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @GoThinkster

Joe Eames

Written by

Joe Eames

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

Thinkster.io

Top Quality Tutorials

Joe Eames

Written by

Joe Eames

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

Thinkster.io

Top Quality Tutorials

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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