3 Ways To Enforce Object Immutability In JavaScript

Ambrose Liew
2 min readMar 19, 2023

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 performObject.preventExtensions()on it and also prevent the deletion of properties.

--

--

Ambrose Liew

Frontend Engineer. Ex-TikTok. Writing straight to the point, no BS articles for you to become The Best Web Developer.