Tip 1: Signal Unchanging Values With const

In this tip, you’ll learn to use const to avoid reassignment and signal your intention to other developers.

Which variable declaration to use?

Modern JavaScript introduced several new variable declarations, which is great. But it also introduced a new problem: Which variable declaration should be the default? And when should we use another type?

In the past, you had only one option for non-global variable assignment: var. Now there are many different options—var, let, and const—and each one has an appropriate usage. Try and keep things simple. In most cases, const is the best choice, not because it allows you to do the most, but because it lets you do the least. It has restrictions that make your code more readable.

ECMAScript is the official technical specification for JavaScript. JavaScript incorporated major syntax changes in ECMAScript 5 and ECMAScript 6, which are referred to as ES5 and ES6. Going forward, the spec will be updated yearly. Most developers now refer to the spec by year, such as ES2017.

Using const

const is a variable declaration that you can’t reassign within the context of the block. In other words, once you establish it, it can’t be changed. That doesn’t mean it’s immutablea value that cannot be changed. If it’s assigned to an array, the items in the array can be changed. We’ll look at this more shortly.

It may seem odd to developers in other languages with a constant assignment that const is the preferred declaration. In those languages, a constant is usually something you’d write in ALLCAPS and only use on rare occasions to denote things that are never going to change, like the first digits of pi.

In JavaScript, though, const is a great default choice precisely because it can’t be reassigned. When you assign a value, you aren’t just declaring a piece of information. You’re also signaling what you plan to do with that information. When you assign values and signal that they won’t be changed, you give future developers (including yourself!) the knowledge that they can forget about a value while they skim the code. And when you’re reading a large amount of code that you haven’t seen before, you’ll be happy that you can forget some of what you read.

Example 1

Let’s assume you’re fixing a bug in a piece of code. You’re skimming through the code to get an idea of how it works and to see if you can guess where the problem might be.

Consider two programs. The first program uses const to assign a variable.

Get hands-on with 1400+ tech skills courses.