JavaScript Quick Tip: How To Make Your Arrays Immutable

JavaScript Quick Tip: How To Make Your Arrays Immutable

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] = 0;
// This too
array.push(4);

If you read my last article, you might already know that you can freeze objects in JavaScript.

If you haven’t read the article: JavaScript allows you to freeze objects and make them immune to changes. This way, you can prevent anyone from mutating the state of your objects.

The best thing about freezing objects is that it also works for arrays.



Freezing Your Arrays

Object.freeze is JavaScript’s API to freeze an object shallowly. This means that the object itself is frozen but not any nested objects.

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] = 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, [3]];
Object.freeze(array);
// This still works
array[2][0] = 4;
// This too
array[2].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!

A picture showcasing the above code

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!

Oliver Jumpertz

Contact

Feel free to contact me

Contact Me

Connect

Subscribe

Join the Newsletter

You will regularly be informed about new content, special offers, and interesting information about software development.

Your data might be transferred to servers located in the USA. By subscribing, you agree to the data transfer. You can revoke your approval at any time by unsubscribing. For more information, please visit the privacy policy.

    We won't send you spam. Unsubscribe at any time.