Immutability is a core concept of functional programming. However, most data structures in standard libraries violate this principle. You can usually add and remove elements to lists or arrays, possibly leading to side effects.
const array = [1, 2, 3]; // This works perfectly fine array = 0; // This too array.push(4);
The best thing about freezing objects is that it also works for arrays.
Freezing Your Arrays
const array = [1, 2, 3]; Object.freeze(array); // This fails silently in lax mode // It throws a TypeError in strict mode ("use strict";) array = 0; // This too array.push(4);
Congratulations, your array is now protected from anyone mutating it. This gives you some safety, especially if you create library code where references are passed back and forth between you and your users.
As stated before, it doesn’t work for nested objects or arrays.
const array = [1, 2, ]; Object.freeze(array); // This still works array = 4; // This too array.push(4);
If you also want your nested arrays to be frozen, you need to recursively freeze the whole array until you hit the last nested layer.
The Whole Tip As An Image
If you like visual content more, or if you want to store it for later, I put all this into one single image for you. I hope you like it!
Before You Leave
If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.
I’d love to count you as my ever-growing group of awesome friends!