In this session, we will be focusing on object immutability.
TABLE OF CONTENT
- Immutability
- seal() method
- freeze() method
Immutability
Immutability simply means can't be modified after creation.
In javascript, value immutability can simply be achieved using const keyword to declare a variable. Unfortunately, const keyword can not make an object immutable.
For Example
So to achieve object immutability, we simple use the freeze() method which helps in hindering an object from being tampered with.
2.Object.seal({theObject: ...}):
this method hinders the extension of an object length. That is, you can not add new property or method to an already sealed object.
For Example:
const names = {
nameOne:'creativeAdams',
nameTwo:'creativeJerry'
}
Object.seal(names);
//or you can use the below method to
Object.preventExtensions(names);
3. Object.freeze({theObject:...}):
this method hinders the changing of an existing property or method and an extension of an object.
For Example:
const names = {
nameOne:'creativeAdams',
nameTwo:'creativeJerry'
}
Object.freeze(names);
Top comments (0)