Make Object Immutable in JavaScript

- 1 minute read

By making an object immutable in JavaScript, properties are frozen and no longer modifiable. JavaScript offers a few built-in methods that help us achieve this.

The Object.seal method blocks new properties from being added and existing properties from being removed:

const obj = {
    color: `red`,
};

Object.seal(obj);

obj.shape = `rectangle`;

console.log(obj.shape); // undefined

To check whether an object has been sealed, you can pass the object to the Object.isSealed method, which will return true or false.

A more “invasive” method is Object.freeze which prevents addition and removal of properties just like Object.seal, while also preventing modification of existing properties:

const obj = {
    color: `red`,
};

Object.freeze(obj);

obj.color = `blue`;

console.log(obj.color); // Logs "red".

Just like Object.isSealed, you can pass an object to the Object.isFrozen method to check whether it has been frozen.

Link to this section Conclusion

On a side note, in strict mode, an error will be thrown if you try to modify an immutable object in a way that is not permitted.

Anyway, I hope this helped you out!