Ensuring Purity – Immutability
In Chapter 4, Behaving Properly, 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 of impurity. Now, after several chapters dealing with many aspects and tools of FP, let’s talk about 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. Still, if we find some way to make data structures immutable (meaning that they cannot be directly changed, except through some interface that never allows us to modify the original data and produces new objects instead), then we’ll have an enforceable solution. In this chapter, we will look at two distinct approaches to working with such immutable objects and data structures:
- Basic JavaScript ways, such as freezing objects...