3 Ways To Enforce Object Immutability In JavaScript
What happens when an Unstoppable Force meets 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.
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.