I am a bit concerned about the comparison.
Andrew Deal
111

When we mutate an object directly, we need to make sure that interested parties are aware of this mutation. E.g. if the todo is displayed in the UI, we need to set up change listeners so that the UI gets notified accordingly.

If we treat objects as immutable, however, then we have eliminated that problem entirely. Since immutable objects cannot be changed after created, the only way to make the UI update is to pass a new updated object to the UI.

Also this makes it easy to track changes. If I kept a previous data, prevData, and then I received a new data, nextData.

  • If the data changed, it is guaranteed that prevData !== nextData. Therefore, there is no need to do defensive copying, since we know that prevData couldn’t mutate in place.
  • If prevData === nextData, then it’s guaranteed that the data is unchanged from the last time, since we know the data couldn’t be mutated in place.

…which is the context of this article (actually, I stated it in the first paragraph). That’s why I didn’t mention the case of mutating the object at all.


But sure, the fastest way to change an object’s state is to directly mutate it. But you have to be very careful.

I use mutations too, but usually just in a small, isolated place. For larger scale, I prefer to keep things immutable so that I don’t even have to think about unintended mutations.

However, plain JavaScript objects are not optimized for immutability. In the article I explained why Immutable.js could clone a very large list/object very quickly and efficiently.

Like what you read? Give Thai Pangsakulyanont a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.