In Chapter 4, Behaving Properly - Pure Functions, when we considered pure functions and their advantages, we saw that side-effects such as modifying a received argument or a global variable were frequent causes for impurity. Now, after several chapters dealing with many aspects and tools of FP, let's get to the concept of immutability: how to work with objects in such a way that accidentally modifying them will become harder or, even better, impossible.
We cannot force developers to work in a safe, guarded way, but if we find some way to make data structures immutable (meaning that they cannot be directly changed, except through some interface that never allows modifying the original data, but produces new objects instead) then we'll have an enforceable solution. In this chapter, we will see two distinct approaches to working with such immutable objects and data structures:
- Basic JS ways, such as freezing objects, plus cloning to create new ones instead...