What if you want to allow changing props of an object, but do not want anyone to add new props? Well, that is what Object.seal
is for.
Objects in Javascript cannot be made immutable by using a const
keyword. const
works on primitives. It can also make sure you don’t reassign value to an object.
|
|
But, const
cannot prevent value in object from being changed.
|
|
Previously you have seen how Object.freeze can be used to render an object completely immutable](/const-and-immutability-in-javascript/).
There are many real-world use cases where -
- You want program to continue changing values of existing props
- Prevent changing the attributes of the existing props
- Prevent further props from being added
- Prevent existing props from being deleted
This is where Object.seal
helps..
|
|
You can also check whether an object is sealed at runtime using Object.isSealed(fruit)
.