HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

2) Dynamically Generated Site Lesson

JavaScript: Prefer Const Over Let

13 min to complete · By Ian Currie

In this lesson, you'll be introduced to const and you'll be advised to prefer it over let.

In the previous JavaScript 101 course you were advised to use let to declare all your variables - this was mainly for simplicity's sake as you can't really go wrong with let. Now, since complex projects are on the horizon, there are some advantages to const over let.

Careful: Const Is a Misleading Name

const is short for "constant". It can be, however, a very misleading name. Sure, you can't reassign values:

const n = 5;
n = 10; // Uncaught TypeError: Assignment to constant variable

You get a TypeError if you try. But, if the variable is an array or an object, you can change an element within it:

const a = [1, 2, 3, 4, 5];
a[0] = 6;
console.log(a); // [6, 2, 3, 4, 5]

const b = { a: 1, b: 2 };
b.a = 0;
console.log(b); // {"a":0, "b":2}

Arrays and objects can be mutated even though they are supposedly "constant".

What can't be done, is assign a new array or object to a const variable:

const a = [1, 2, 3, 4, 5];
a = [6, 2, 3, 4, 5]; // Uncaught TypeError: Assignment to constant variable.

So as long as you are aware that const is not a failsafe, you'll be fine.

Technically speaking, the binding of a const variable is immutable. But since variables that are arrays or objects are references to memory locations, you can mutate the value at that location. The reference is immutable, but the value is not.

Use Const For Better Developer Experience

const can protect the developer from mistakes. So, for now, you will get started on your journey into using const.

If you are reading a large codebase and see const everywhere, when you see a let variable, you know that it will be a changing variable. This can code more readable at a glance and predictable.

This guard rail is one of those things that doesn't necessarily make the code any better or worse in terms of performance. What it does do is make the developer experience better. It produces code that is more logical and easier to refactor into discrete components and pure functions. Code that can give you meaningful error messages instead of silently failing.

Debate: const vs let

You'll often find a lot of debate on whether using const is worth it. A member of the React core team, Dan Abramov has an article on just this topic, on let vs const, and he generally prefers let, but presents a nuanced view of the debate. Here is a summary of his arguments:

Arguments for preferring const:

  1. Simplicity in Decision-Making: Using const as a default reduces the mental load of choosing between let and const.
  2. Avoiding Bugs: const reduces the risk of bugs in longer functions or closures since variables can't be reassigned.
  3. Understanding Mutation: Preferring const helps clarify the distinction between variable mutation and assignment, an important concept in JavaScript.
  4. Avoiding Meaningless Assignments: In certain scenarios, using const makes sense since the values should not be reassigned.
  5. Potential Performance Benefits: Some believe that const could lead to performance optimizations in JavaScript engines.

Arguments against preferring const:

  1. Loss of Intent: Using const indiscriminately can obscure the intent, especially when it’s crucial that a variable should not be reassigned.
  2. Confusion with Immutability: Can lead to confusion between immutability and variable reassignment, which are different concepts.
  3. Pressure Against let: A const-first approach might discourage the use of let even when it's more appropriate.
  4. Reassignments Not Always Problematic: Reassignments are not inherently bad and often don’t cause bugs in well-structured code.
  5. No Clear Performance Gains: Abramov suggests that JavaScript engines are already optimized to handle variables that are only assigned once, regardless of whether var, let, or const is used.

He is neutral, on the whole, mentioning that if he is on a team that prefers const, he will adapt to that. Using const is cheap, and does provide some guardrails that will help you to think about your code. It also is just another way to add a bit of expressiveness to your code. Just be sure to understand that const doesn't necessarily mean "constant".

For students of this course, you'll be using const as a default and use let when you need to reassign a variable.

Ways to make Objects immutable

Sometimes you want to make an object immutable. If you want to make an object immutable, there are actually a few methods that can come in handy. You can use Object.freeze(), Object.seal(), or Object.preventExtensions(). These methods are not commonly used, but it's good to know that they exist.

Use Object.freeze() to Make Objects Immutable

If you do want to include some extra guardrails, you can use Object.freeze() to make an object immutable:

const a = Object.freeze({ a: 1, b: 2 });
a.a = 0; // (no error, acts as if it changes the value, but doesn't)
console.log(a); // {"a":1, "b":2}

Use Object.seal() to Make Objects Immutable

Object.seal() is a bit less strict than Object.freeze(). It will allow you to mutate the values of the object, but not add or remove properties:

const a = Object.seal({ a: 1, b: 2 });
a.a = 0; // OK
a.c = 3; // (no error, acts as if it adds key, but doesn't)
console.log(a); // {"a":0, "b":2}

Use Object.preventExtensions() to Make Objects Immutable

Object.preventExtensions() is even less strict than Object.seal(). It allows you to mutate and delete properties of the object, but it does not allow adding new properties:

const a = Object.preventExtensions({ a: 1, b: 2 });
a.a = 0; // OK
a.c = 3; // (no error, acts as if it adds key, but doesn't)
delete a.a; // OK
console.log(a); // {"b":2}

Use Object.isFrozen(), Object.isSealed(), and Object.isExtensible() to Check the State of an Object

You can use Object.isFrozen(), Object.isSealed(), and Object.isExtensible() to check the state of an object:

const a = Object.freeze({ a: 1, b: 2 });
console.log(Object.isFrozen(a)); // true
console.log(Object.isSealed(a)); // true
console.log(Object.isExtensible(a)); // false

Strict Mode

Strict mode is a way to opt-in to a restricted variant of JavaScript. It is also a way to make your code more secure, and to avoid some common mistakes. If you were using strict mode, the methods shown above would throw errors instead of silently failing to assign a new value to the frozen object, for instance.

You can opt-in to strict mode by adding the following line to the top of your JavaScript file:

'use strict';

You can read more about strict mode in the MDN article on Stict Mode. It is a good idea to use strict mode in your code (more guardrails and better practice), but it is not required for this course.

Summary: Why Is It Better To Define Variables With the Javascript Const

You've expanded your understanding of variable declarations in JavaScript, focusing on why const can a better choice than let. You've:

  • Realized that const doesn't enforce immutability on objects or arrays, but it does prevent reassigning a new reference to the variable.
  • Understood the importance of using const to communicate that a variable should not be and will not be reassigned, which can make your code easier to read and maintain.
  • Engaged with the debate between const vs. let, seeing that there are valid points on both sides and the choice often comes down to team preference and coding style.
  • Discovered methods to enforce object immutability, like Object.freeze(), Object.seal(), and Object.preventExtensions(), each offering different levels of restriction.
  • Briefly touched upon the concept of JavaScript's strict mode, which helps in writing safer and more predictable code, although it's not a requirement for this course.

By default, you'll be using const in your code from now on, switching to let only when you have a variable whose value will change over time.