The Concept of Immutability in JavaScript

The Concept of Immutability in JavaScript

Daily short news for you
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » Read more
  • It's been a long time since I've read such a heartfelt article The many, many, many JavaScript runtimes of the last decade. In the article, the author recounts the journey of the development of the JavaScript runtime environment, noting that today we have and are seeing JavaScript present in many areas. Additionally, the author also touches on a lot of peripheral knowledge; just a little reading opens up so many new discoveries 🤓

    » Read more
  • Android has seen the emergence of a Tapjacking attack. Essentially, malicious applications exploit your permission to access sensitive information on the device without your knowledge. You can learn more details here TapTrap.

    This reminds me of the DoubleClickjacking attack mentioned earlier in this Threads which is quite alarming.

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...