DEV Community

Ambrose Liew
Ambrose Liew

Posted on

3 Ways To Enforce Object Immutability In JavaScript

What happens when an Unstoppable Force meets an Immutable Object?

An Immutable Object

Immutability

In JavaScript, Object Immutability means that once you have made an object immutable, its properties cannot be added, deleted, or modified at any time.

This is important because it helps prevent unwanted side effects from occurring, making your code more predictable and easier to reason about.


Here are 3 ways you can make an object immutable in JavaScript, ordered by the level of integrity they retain.

Object.preventExtensions()

Object.preventExtensions() will prevent new properties from being added to an object.

Demo of Object.preventExtensions()

However, it still allows the deletion of properties and modification of values from an object.

You can check whether an object is extensible by using Object.isExtensible()

Object.seal()

Object.seal() will perform Object.preventExtensions() on it and also prevent the deletion of properties.

Demo of Object.seal()

However, it still allows the modification of values of an object.

You can check whether an object is sealed by using Object.isSealed()

Object.freeze()

Object.freeze() will perform Object.seal() on it and also prevent the modification of values of an object.

Demo of Object.freeze()

You can check whether an object is frozen by using Object.isFrozen()

Object.freeze() is the highest level of integrity that JavaScript offers.

Extras

  • All of the above methods are applied shallowly on the object. This means that if you have an object within an object, the inner object would still be mutable.
  • To perform a deep operation instead of a shallow one, you have to implement your own recursive function. MDN has provided a working example.

MDN’s recursive deep freeze example

You can play with the examples above in this JSFiddle.

If you felt that you have learned something new, do feel free to follow 🥰, react 💖 or write a comment ✍️!
It helps makes me create and share more valuable content for you to become a better Web Developer! 🤗

Top comments (0)