What does immutable mean in Javascript? Explaining by the simple example

Last Updated On

If you're asking this question you probably already know how it's important (whether it's for the job interview or for daily programming routing) to understand immutability. The goal here is to provide you real-world example to help grasp this idea quicker. I also promise that it will be the last time when I use word immutable before I get to the key point.

Use case with string processing

One of the most popular use cases where it's important to understand this idea is string processing.

Real world task (simplified):

Parse a URL and save its relative path to a separate variable to recreate folder structure in Linux and Windows formats later on.

For example, when parsing https://example.com/products/popular/bikes/road-bikes/index.html

  1. One result should be products/popular/bikes/road-bikes (for Linux).
  2. Another result should be products\popular\bikes\road-bikes (for Windows).

Let's walk through the solution:

As a result subpath will be equal to:

The question is - what does happen to windowsSubpath if we applied exactly the same method as for linuxSubpath just with different separator?

The actual problem here is in the splice() method. It actually modifies or mutates the original value of urlParts array by removing selected items from it. The urlParts.splice(3, urlParts.length - 4).join('/'); removed 4 items and instead of having:

started to have this value globally:

From now on, everybody who wants to access urlParts will get modified value instead of original one and it's safe to say, that splice() is a mutable function.

The alternative way to solve this problem is by using slice() function which takes the index of starting element you want to extract from and ending index:

The result will be:

In this case, it's reasonable to say that slice() is immutable function, i.e. does not modify or mutate the original value of urlParts.

Disclaimer for perfectionists: It's clear that this problem can be solved in a hundred different ways (including one-line solution), but this approach clearly highlights the main problem of this article.

Conclusion

When working with pure javascript applications and front-end frameworks there is always a case when it's needed to provide only filtered part of some sort of data: filter posts by tags in a blog, display flights during selected rage on airlines portal, etc. The filtered data is condensed version of the original data and it's being created when a new filter or sorting algorithm is applied. As it's pretty obvious, the original data shouldn't be modified. It's important to understand which functions modify the initial data and which don't. Without a proper understanding of this concept your code might be easily broken and even worse, lead to unwanted results which are very difficult to debug.