The Concept of Immutability in JavaScript

The Concept of Immutability in JavaScript

Daily short news for you
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more
  • CloudFlare has introduced the pay per crawl feature to charge for each time AI "crawls" data from your website. What does that mean 🤔?

    The purpose of SEO is to help search engines see the website. When users search for relevant content, your website appears in the search results. This is almost a win-win situation where Google helps more people discover your site, and in return, Google gets more users.

    Now, the game with AI Agents is different. AI Agents have to actively seek out information sources and conveniently "crawl" your data, then mix it up or do something with it that we can't even know. So this is almost a game that benefits only one side 🤔!?

    CloudFlare's move is to make AI Agents pay for each time they retrieve data from your website. If they don’t pay, then I won’t let them read my data. Something like that. Let’s wait a bit longer and see 🤓.

    » Read more
  • Continuing to update on the lawsuit between the Deno group and Oracle over the name JavaScript: It seems that Deno is at a disadvantage as the court has dismissed the Deno group's complaint. However, in August, they (Oracle) must be held accountable for each reason, acknowledging or denying the allegations presented by the Deno group in the lawsuit.

    JavaScript™ Trademark Update

    » Read more

Issue

Variables are an essential component in most programming languages. When we talk about variables, we often think of a syntax that includes a keyword, variable name, data type, and its initial value. For example, a variable in JavaScript is declared as follows:

let name = "2coffee.dev";

Variables - as the name suggests, their values can be changed through assignment. Changing the value of a variable allows programmers to reuse variable names, save memory, and increase flexibility in programming. Imagine the name variable in the example above, when it reaches line x, the old value is no longer effective and needs to be replaced with "https://2coffee.dev" before returning the data to the user, for example. In summary, changing the value of a variable is quite normal.

However, things can become complicated when there are more variables in the code. Creating multiple variables is often proportional to the complexity of the problem-solving logic. I once wrote a function that used dozens of different variables. Just imagine if all of those variables were constantly changing, what would the data flow look like?

Simple! Just follow the rule of declaring non-changing data with the const keyword, then the variable will never be reassigned, const, also known as declaring a constant, means that it cannot be changed. Usually, when creating a variable, I habitually type const because of the benefits it brings: limiting the modification of variable data.

But in the world of JavaScript, nothing is impossible. When using const for variables that hold object types like Object, Array... const prevents value assignment, but it cannot prevent changes to the data inside the object.

const website = {
  name: "2coffee.dev",  
};

website.name = "https://2coffee.dev";
console.log(website.name); // https://2coffee.dev

In this case, the data starts "dancing" in your logic flow. Many people think, "What's the big deal here, data changes are normal..." then I'm sure they have never debugged and maintained a function with dozens of variable types. Changing data means you have to observe them all the time, when looking at the code and cannot predict at line x, position y, what data does the data variable hold, then it is highly likely that maintenance will be extremely difficult in the future. If you are the author of that piece of code, you can confidently fix it, but if it is someone else, they may unintentionally create some other errors while trying to change the "data flow" that you created earlier.

So what is the lesson learned?

Immutability

Immutability in JavaScript programming refers to the ability of variables and data structures to remain unchanged after they have been created. This means that their values cannot be changed once they have been determined. Immutability provides stability and easy tracking in source code, prevents unwanted changes, and provides a foundation for easy testing and maintenance.

In JavaScript, we often use the const keyword to create immutability on primitive data types, and Object.freeze for object data.

const website = {
  name: "2coffee.dev",  
};

Object.freeze(website);

website.name = "https://2coffee.dev";
console.log(website.name); // 2coffee.dev

In the example above, after using Object.freeze(website), the website object is immediately "frozen" and the data in its properties cannot be changed anymore, no matter how many times we try to reassign them. Great, then doesn't const for primitives and Object.freeze for objects solve all the issues with immutability?

Unfortunately, Object.freeze only freezes the object shallowly, meaning if there is a property with a data type of an object inside website, it can still be changed.

const website = {
  name: "2coffee.dev",  
  props: {
    color: "black",  
  }
};

Object.freeze(website);

website.props.color = "white";
console.log(website.props.color); // white

To solve this problem, we have to implement a function that is capable of deep freezing an object, meaning it must freeze the properties of the properties... of the object.

function deepFreeze(object) {
  // Retrieve the property names defined on object
  const propNames = Reflect.ownKeys(object);

  // Freeze properties before freezing self
  for (const name of propNames) {
    const value = object[name];

    if ((value && typeof value === "object") || typeof value === "function") {
      deepFreeze(value);
    }
  }

  return Object.freeze(object);
}

const website = {
  name: "2coffee.dev",  
  props: {
    color: "black",  
  }
};

deepFreeze(website);

website.props.color = "white";
console.log(website.props.color); // black

Pros and Cons of Immutability

When data is not changed, we can observe it at any time, reuse it without worrying about being changed somewhere else. In the past, I used to try to change the data inside an array or an object, then the object was used elsewhere and caused data inconsistency issues, leading to completely broken logic.

Minimizing errors during development, one of which can be mentioned as Some Notes on Object Reference in JavaScript. Forgetting can be so annoying!. When accidentally changing reference data, it also changes everywhere that uses that data.

Easy testing, increased security because data is not changed from somewhere in the code.

However, immutability also brings many issues, the most prominent of which is the memory cost, as every time the data is changed, a new object needs to be created to hold all the new data. Memory increases, which also affects performance, increases complexity, and requires more code to be written for a simple function.

Advice

JavaScript is a flexible language, not bound by data types and very "liberal" in writing style. There will be projects where you see them strictly applying immutability and vice versa, immutability should only be used where necessary.

Based on personal experience, I always use const when declaring all variables, and in cases where the variable needs to be reassigned, consider a different approach to limit the modification of variable data.

When working with Array or Object data, limit direct changes to the data inside them. If the data needs to change too much compared to the current state, it is best to create a variable with a new set of data. Try to deep copy to avoid future "object reference" issues, clone | npm can be a useful library for you.

If stricter measures are needed, consider using Object.freeze or libraries that support creating immutable objects such as Immutable.js. Then everyone will work under the same set of rules, avoiding "mutations" of data beyond control.

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...