Last active
September 20, 2018 02:56
-
-
Save LostinOrchid/e9baa780bebe24ea7fbfa9bb07f5b6d5 to your computer and use it in GitHub Desktop.
Warning on object assign mutation
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
var a = { | |
one: { | |
nested: 'a', | |
onlyInA: 'a', | |
nestedMore: { what: 'a' }, | |
}, | |
aOnly: 'a only', | |
}, b = { | |
one: { | |
nested: 'b', | |
onlyInB: 'b', | |
nestedMore: { what: 'b' }, | |
}, | |
bOnly: 'b only', | |
}, | |
// Will copy the reference instead of value of the first argument | |
// in this case the 'a' variable | |
c = Object.assign(a,b); | |
// Which means if you mutate 'c', 'a' will also mutate. | |
c.aOnly = 'bug from c'; | |
c.bOnly = 'bug from c'; | |
c.one.nested = 'c'; | |
c.one.nestedMore.what = 'c'; | |
console.log(c === a); // true | |
console.log({a,b,c}); | |
// To avoid this. | |
// You could either use empty {} object as the first paramater of the Object.assign function | |
// or use the spread syntax to create a clone (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment