The “const” how to use it

Master raj
7 min readMay 11, 2023

--

Exploring the difference between assignment and mutation in JavaScript

The const keyword in JavaScript is used to declare a constant. Constants are often thought of as "variables that can't change":

const hi = 5;hi = 10;// 🛑 Uncaught TypeError: Assignment to constant variable.console.log(hi);// -> 5

Curiously, though, when I create an object using const, I’m free to change it:

const person = {  name: 'Hassan',};person.name = 'Sujata';// Seems to work?? 🤔console.log(person);// -> { name: 'Raj' }

How come I was able to change the person variable? I used const!

To make sense of this apparent contradiction, we need to learn about the difference between assignment and mutation. This is a core concept in JavaScript, and so many things make more sense when you have a clear understanding of this distinction.

Let’s go!

Intended audience:-

This blog post is intended for beginner/intermediate JavaScript developers. I do assume that you’ve been working with JavaScript for at least a few weeks and are comfortable with the basic syntax.

So, here’s a perfectly-valid JavaScript program:

5;

Here’s another one:

['apple', 'banana', 'cherry'];

In both of these examples, I’m creating some stuff. A number, and an array. When the code runs, this data will be created and stored in the computer’s memory.

These programs aren’t terribly useful, however. I’m creating some data, but I have no way of accessing it!

Variables allow us to stick a label on the stuff we create, so that we can reference it later:

// Create it now...
const fruits = ['apple', 'banana', 'cherry'];
// ...and access it later:
console.log(fruits);
// -> ['apple', 'banana', 'cherry']

When I was first learning to program, I thought that the code was executed from left to right: first we create a fruits variable, like an empty box, and then we assemble our array within that box.

“Variables”?

In this tutorial, I’m going to use the term “variable” to refer to any names given to data, regardless of whether we use let or const:

// This is a variable:
let age = 26;
// This is a variable too:
const favouriteColor = 'hotpink';

I recognize that this is confusing; the term “variable” implies that something can vary! Unfortunately, “variable” is the established umbrella term in JavaScript, including both let and const (as well as the deprecated var keyword).

Reassigning our labels

When we use the let keyword to create a variable, we’re able to change which “thing” that label refers to.

For example, we can point our fruits label at a new value:

This is known as re-assignment. We’re saying that actually, the fruits label should refer to an entirely different value:

// We start with a labeled array:
let fruits = ['apple', 'banana', 'cherry'];
// ⚠️⚠️⚠️⚠️
// Pick a different option from the list above
// to see how it translates in code!

We're not modifying the data, we're modifying the label. We're detaching it from that original array, and connecting it to a new one.

By contrast, variables created with const cannot be reassigned:

This is the fundamental difference between let and const. When we use const, we create an indestructible link between a variable name and a piece of data.

Here's the thing, though: we're still allowed to modify the data itself! As long as the label remains intact.

For example, with an array, we can add/remove items from that array without issue. The fruits variable is still connected to the same array:

In code, this would look something like this:

// Point the `fruits` label at this array:
const fruits = ['apple'];
// ⚠️ Click the “Add Item” button to mutate the array

This is known as mutation. We're editing the value of the array by adding / removing items.

Here's another example, using an object instead of an array. We can edit the keys/values within the object, as long as the label keeps pointing to the same object:

You can edit the title property. This is equivalent to the following JS code:

const event = {
title: 'Change me!',
startsAt: '2023-05-29T16:00:00Z',
duration: 4,
confirmed: true,
};
event.title = "Hello "

There's a fundamental distinction between re-assignment (pointing a variable name at a new thing) and mutation (editing the data within the thing).

When we create a constant with const, we can be 100% sure that the variable will never be re-assigned, but no promises are made when it comes to mutation. const doesn't block mutation at all.

There's one more wrinkle here, too: “primitive” data types like strings and numbers are immutable. This makes things even more confusing. We'll discuss in the next section.

  • Freezing objects and arrays
    So, frustratingly, the const keyword won't protect us from mutation. Is there some other way to guarantee that our data won't be edited?

There is! It's a handy-dandy method called Object.freeze():

// With arrays:
const arr = Object.freeze([1, 2, 3]);
arr.push(4);
console.log(arr);
// -> [1, 2, 3]
// With objects:
const person = Object.freeze({ name: 'Hassan' });
person.name = 'Sujata';
console.log(person);
// -> { name: 'Hassan' }

As far as I know, Object.freeze() is bulletproof. There's no way to modify an object/array that has been frozen using this method.

Also, if you use TypeScript, you can use the as const assertion to accomplish a similar result:

const arr = [1, 2, 3] as const;
arr.push(4);
// 🛑 Error: Property 'push' does not exist
// on type 'readonly [1, 2, 3]'.

Like all static types, these guards disappear when the code is compiled to JavaScript, and so this doesn't quite offer the same amount of protection as Object.freeze(). Depending on your use case, though, it may be sufficient!

Thanks to Matt Pocock for the tip!

Primitive data types
So far, all of the examples we've seen have involved objects and arrays. But what about if we have a “primitive” data type, like a string, a number, or a boolean value?

Let's use a number as an example:

let age = 36;
age = 37;

How should we interpret this? Are we reassigning the age label to a new value, or are we mutating this number, editing 36 to be 37?

Here's the deal: all primitive data types in JavaScript are immutable. It's impossible to "edit" the value of a number. We can only reassign the variable to a different value.

Here's how I like to think about it: Pretend that there's a big list of all possible numbers. We've assigned our age variable to the number 36, but we can point it at any other number in our list:

To be clear, the browser doesn't literally have a big index of all possible numbers. The point I'm hoping to illustrate here is that the numbers themselves can't be changed. We can only change which number the label is pointing to.

This is true for all primitive value types, including strings, boolean values, null, and so on.

A thought experiment
As mentioned, primitive values are “immutable” in JavaScript; they can't be edited.

But what if they could? What would the syntax be like, if the numbers themselves could be mutated?

It would look something like this:

// Edit the value of the number 36:
36 = 37;
// The number 36 no longer exists!
console.log(36); // 37

  • The whole idea with “mutation” is that it fundamentally changes that value. When we mutate an object, we change the “essence” of that object, and we can see those changes when we reference them:
const me = { age: 36 };
me.age = 37;
console.log(me);
// -> { age: 37 }

And so, if we could mutate primitive values in JavaScript, it would mean essentially overwriting certain numbers so that they could never be referenced again!

This would obviously be confusing and unhelpful, which is why primitives are immutable in JavaScript.

Additional resources
JavaScript is a deceptively tricky language, and it takes a long time to get really comfortable with it!

Here are some additional resources you might find useful:

https://medium.com/@masterrajpatel/-25f3ccc4e487

https://medium.com/@masterrajpatel/git-cheat-sheet-with-71a3e70ac04d

If you enjoyed reading this blog, please share it with your friends and make sure to subscribe to our YouTube channel for more exciting content. Help us spread the word about our expertise in MERN stack development, cloud computing, React Native, and Next.js, and stay tuned for more informative articles to come. Together, we can take the tech world by storm!

In the Mern Stack Projects section you can find tutorials, tips, cheat sheets, and other projects. Our talks also focus on React Frameworks like NextJs,AWS Cloud So join us today to keep up with the latest technology🩷
📠 🏅:- Mern Stack Projects
🎦 🥇:- Jara diary - YouTube 🚦
🎦 🥈 :- Errormania - YouTube 🚦
On GITHUB :- raj-28 (Raj) (github.com)
💌 Do Subscribe To Our Mailing List To stay Updated With All New Blogs 👍
…………🚦…🛣… ……………🚧🛑………………..▶……………….️
Use Emojis From Here In Case You Need Any….🚦🛣️🥇🥈🥉🏅🎖️🎦👍
Fetch API : Again are you using that right🫸
The Fetch API is a powerful tool that allows you to send HTTP requests to servers and receive responses in JavaScript…medium.com
Axios Network Error when making HTTP request [Solved] |
# Axios Network Error when making HTTP request [Solved]medium.com

--

--

Master raj

Certified MERN Stack Developer from Infosys, now sharing expertise on #InCloudByRK. Proficient in MERN Stack, AWS, GCP, Azure DevOps. Let's level up!