JavaScript Quick Tip: How To Make Your Objects Immutable

JavaScript Quick Tip: How To Make Your Objects Immutable

Freezing Any Object

Subscribe to my newsletter and never miss my upcoming articles

JavaScript's objects are mutable by default. If you don't take any action, anyone can mutate the state of objects you create.

const obj = {
  prop: 1
};

obj.prop = 2; // obj.prop is now 2

Especially in functional programming, immutability is a core requirement. Instead of changing the state of existing objects repeatedly, you create new objects, copy over what you don't change, and then apply your changes to the properties left.

Enter Object.freeze

JavaScript gladly has an API to freeze your objects. This prevents all forms of mutation and can give you some safety back.

const obj = {
  prop: 1
};

Object.freeze(obj);

// silently fails in lax mode
// throws a TypeError in strict mode ("use strict";)
obj.prop = 2;

What Object.freeze, however, actually does is only doing a shallow freeze. This means that if you have nested objects that aren't frozen, you don't get a fully frozen object.

const obj = {
  prop: 1,
  nested: {
    prop: 0
  }
};

Object.freeze(obj);

// This works perfectly fine
obj.nested.prop = 1;

When you want nested objects to be frozen, as well, you would also have to freeze them.

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!

Interested in reading more such articles from Oliver Jumpertz?

Support the author by donating an amount of your choice.

Recent sponsors
#javascript#typescript#howtos
 
Share this