Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create immutable object in javascript

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).

like image 903
Vinícius Mussato Avatar asked Oct 20 '17 16:10

Vinícius Mussato


2 Answers

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
like image 143
Craig Ayre Avatar answered Oct 06 '22 05:10

Craig Ayre


For Immutable object we can use below approches

  1. Object.freeze()
  2. To enforce object immutability while update the object make sure to
  3. use Object.assign({},a,{foo:'bar'}) rather than a.foo='bar'
  4. we can use 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}
like image 31
pa1 Raju Avatar answered Oct 06 '22 06:10

pa1 Raju