I have a routine where I receive some data from an api. I'd like to store this data in an object, but after that i want to "lock" this object and not allow any change to the properties or their values after that point. Is that possible? (If possible using only ES5).
If you wish for an object to not be able to be modified you can use Object.freeze
.
The
Object.freeze()
method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed, it also prevents the prototype from being changed. The method returns the object in a frozen state.
If you simply want to prevent a variable from being reassigned you can use const
(ES6), however note that:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
E.g, the following is perfectly valid
const a = { x: 7 }
a.x = 9
console.log(a.x) // 9
However, trying to reassign a variable declared with const
will throw a TypeError
:
const a = 5
a = 7
For Immutable object we can use below approches
Object.freeze()
Object.assign({},a,{foo:'bar'})
rather than a.foo='bar'
spread(...)
operator. See example:
var person={name:'pavan',age:26}
var newPerson={...person,name:'raju'}
console.log(newPerson ===person) //false
console.log(person) //{name:'pavan',age:26}
console.log(newPerson) //{name:'raju',age:26}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With