You can prevent objects from mutating through two methods:
Object.assignassignment
Object.assign
Object.assign lets you combine two (or more) objects into a single one. It has the following syntax:
const newObject = Object.assign(object1, object2, object3, object4)newObject will contain properties from every object you pass into Object.assign.
const papayaBlender = { canBlendPapaya: true }const mangoBlender = { canBlendMango: true }
const fruitBlender = Object.assign(papayaBlender, mangoBlender)
console.log(fruitBlender)// {// canBlendPapaya: true,// canBlendMango: true// }If two conflicting properties are found, the property in a later object overwrites the property in an earlier object.
const smallCupWithEar = { volume: 300, hasEar: true,}
const largeCup = { volume: 500 }
// In this case, volume gets overwritten from 300 to 500const myIdealCup = Object.assign(smallCupWithEar, largeCup)
console.log(myIdealCup)// {// volume, 500,// hasEar: true// }But beware! When you combine two objects with Object.assign, the first object gets mutated. Other objects donโt get mutated.
console.log(smallCupWithEar)// {// volume, 500,// hasEar: true// }
console.log(largeCup)// {// volume, 500// }Preventing Object.assign from mutating objects
You can pass a new object as your first object to prevent existing objects from mutating. Youโll still mutate the first object (which is empty), but thatโs OK since this mutation doesnโt affect other objectsโit wonโt change external state.
const myIdealCup = Object.assign({}, smallCupWithEar, largeCup)But Object.assign copies references to nested objects
The problem with Object.assign is that it performs a shallow mergeโit copies properties directly from one object to another. When it does so, it also copies references to any objects.
Letโs explain this statement with an example.
Suppose you buy a new sound system. The system lets you change three settings:
- Power (turned on or off)
- Volume (through a number)
- Loudness (through a number)
const defaultSettings = { power: true, soundSettings: { volume: 50, bass: 20, },}You want to invite your friends to a party. You know some of them love loud music, so you create a preset thatโs guaranteed to wake your neighbors.
const loudPreset = { soundSettings: { volume: 100, },}When you invite your friends over to the party, you want to preserve your existing presets (so you can switch back quickly). You choose to combine loudPreset with the default settings.
const partyPreset = Object.assign({}, defaultSettings, loudPreset)But partyPreset sounds weird. The volume is loud enough, but the bass is non-existent. When you inspect partyPreset, youโre surprised to find that thereโs no bass in it!
console.log(partyPreset)// {// power: true,// soundSettings: {// volume: 100// }// }This happens because JavaScript copies the reference to the soundSettings object. Since both defaultSettings and loudPreset have a soundSettings object, the one that comes later gets copied into the new object.
If you change partyPreset, loudPreset will mutate accordinglyโevidence that partyPreset links to loud presetโs soundSettings object.
partyPreset.soundSettings.bass = 50
console.log(loudPreset)// {// soundSettings: {// volume: 100,// bass: 50// }// }You need another method to ensure nested objects (objects in objects) donโt get passed over to partyPreset. Enter assignment.
Assignment
assignment is a library made by Nicolรกs Bevacqua from Ponyfoo, which is a great source for JavaScript knowledge. It helps you perform a deep merge without having to worry about mutation. Aside from the method name, the syntax is the same as Object.assign.
// Perform a deep merge with assignmentconst partyPreset = assignment({}, defaultSettings, loudPreset)
console.log(partyPreset)// {// power: true,// soundSettings: {// volume: 100,// bass: 20// }// }//assignment copies over values of all nested objects, which prevents your existing objects from getting mutated.
If you try to change any property in partyPreset.soundSettings now, youโll see that loudPreset remains as it was.
partyPreset.soundSettings.bass = 50
// loudPreset doesn't get mutatedconsole.log(loudPreset)// {// soundSettings {// volume: 100// }// }Note: assignment is just one of many libraries that help you perform a deep merge. Other libraries, including lodash.mereg and merge-options), can help you do it too. Feel free to choose from any of these libraries.
Should you always use assignment over Object.assign?
You can use Object.assign if youโre not merging objects with nested objects. Thereโs no harm in using it as long as you know what youโre doing.
If you need to assign objects with nested properties, always use assignment over Object.assign.
Wrapping up
Object.assign can be used to prevent objects from mutating.
Take note that Object.assign can only prevent direct properties from mutating. If you need to merge objects with nested properties, use assignment (or other libraries that do the same thing) instead of Object.assign.
Exercise
- Combine two objects with
Object.assign. - Combine two objects with
assignment.
Combine two objects with Object.assign.
const object1 = { wheels: 4 }const object2 = { type: 'car' }
const merged = Object.assign({}, object1, object2)Combine two objects with assignment.
// From https://github.com/bevacqua/assignment/blob/master/assignment.jsfunction assignment(result) { var stack = Array.prototype.slice.call(arguments, 1) var item var key while (stack.length) { item = stack.shift() for (key in item) { if (item.hasOwnProperty(key)) { if ( typeof result[key] === 'object' && result[key] && Object.prototype.toString.call(result[key]) !== '[object Array]' ) { if (typeof item[key] === 'object' && item[key] !== null) { result[key] = assignment({}, result[key], item[key]) } else { result[key] = item[key] } } else { result[key] = item[key] } } } } return result}
const object1 = { wheels: 4 }const object2 = { type: 'car' }
const merged = assignment(object1, object2)Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson