Created
April 29, 2019 18:23
-
-
Save splincode/acc02a2af0078a1700af3615e02572b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
INCORRECT CHANGES (deep mutation) | |
*/ | |
const animals = { | |
zebra: { | |
food: ['leaves', 'bark'], | |
name: 'zebra' | |
}, | |
panda: { | |
food: [], | |
name: 'panda' | |
} | |
}; | |
const copy = { ...animals }; | |
copy.panda.food.push('leaves'); // bad | |
console.log(animals.panda.food); // ['leaves'] | |
console.log(copy.panda.food); // ['leaves'] | |
/* | |
CORRECT CHANGES (deep spread) | |
*/ | |
const animals = { | |
zebra: { | |
food: ['leaves', 'bark'], | |
name: 'zebra' | |
}, | |
panda: { | |
food: [], | |
name: 'panda' | |
} | |
}; | |
const copy = { | |
...animals, | |
panda: { | |
...animals.panda, | |
food: [ | |
...animals.panda.food, | |
'leaves' | |
] | |
} | |
}; | |
console.log(animals.panda.food); // [ ] | |
console.log(copy.panda.food); // ['leaves'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment