There are multiple ways to keep objects safe in JavaScript (ES6) by making them immutable. This reduces side-effects and unpredictable behavior. But what does what? There are four options available, which I will show you in some simple examples below.
Note: This also applies to TypeScript.
Restricting Objects
1 — const
The most common and well-known way to keep an object from being changed is by using theconst
keyword. You can’t assign the object to something else, unlike let
and var
, but you can still change the value of every property, delete a property, or create a property.
const myObject = { | |
firstProp: true, | |
secondProp: 'Yes' | |
} | |
myObject = false // not allowed (assign) | |
delete myObject.firstProp // allowed (delete) | |
myObject.secondProp = 'No' // allowed (update) | |
myObject.thirdProp = 'Yes' // allowed (add) |
2—preventExtensions
To be a bit stricter we use Object
methods. The first object method to prevent changing object properties is called preventExtentions
. This will prevent adding new properties to the object, updating, and deleting existing properties is still allowed.
const myObject = { | |
firstProp: true, | |
secondProp: 'Yes' | |
} | |
Object.preventExtensions(myObject); | |
myObject.isExtensible() // false | |
myObject = false // not allowed (assign) | |
delete myObject.firstProp // allowed (delete) | |
myObject.secondProp = 'No' // allowed (update) | |
myObject.thirdProp = 'Yes' // not allowed (add) |
3 — seal
The next method is seal
. This will prevent adding new and deleting existing properties to and from the object, but updating existing properties is still allowed.
const myObject = { | |
firstProp: true, | |
secondProp: 'Yes' | |
} | |
Object.seal(myObject); | |
myObject.isSealed() // true | |
myObject = false // not allowed (assign) | |
delete myObject.firstProp // not allowed (delete) | |
myObject.secondProp = 'No' // allowed (update) | |
myObject.thirdProp = 'Yes' // not allowed (add) |
4 — freeze
And the last one is called freeze
. This will prevent changing anything to the object. With freeze
you are sure it’s not modified anywhere in your code.
const myObject = { | |
firstProp: true, | |
secondProp: 'Yes' | |
} | |
Object.freeze(myObject); | |
myObject.isFrozen() // true | |
myObject = false // not allowed (assign) | |
delete myObject.firstProp // not allowed (delete) | |
myObject.secondProp = 'No' // not allowed (update) | |
myObject.thirdProp = 'Yes' // not allowed (add) |