fbpx

21 Jan /Immutable Objects using Object.assign

Posted by Dom Miller

Is immutability important? Mutating data can produce code that’s hard to read and error prone. But we can avoid this mess using vanilla javascript’s ES6 feature Object.assign!

Let’s look at the problem….

var obj1 = { key: 'some value' };

var obj2 = obj1;
obj2.key = 'another value';

console.log( obj1 === obj2) // true
console.log( obj1.key ) // 'another value'

When we changed obj2’s key property, it also changed obj1’s key property. No bueno! The solution:

var obj1 = { key: 'some value' };

var obj2 = Object.assign( {}, obj1, { key: 'another value' });

console.log( obj1 === obj2) // false
console.log( obj1.key ) // 'some value'
console.log( obj2.key ) // 'another value'

As you can see we changed obj2’s key property and it left obj1’s state intact! Now that’s immutable! Object.assign takes objects as its parameters and passing in an empty object as the ‘target’ keeps our ‘source’ objects intact.

Object.assign is widely supported by desktop and mobile browsers, please check Mozilla for more info.