Skip to content

Instantly share code, notes, and snippets.

@LostinOrchid
Last active September 20, 2018 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LostinOrchid/e9baa780bebe24ea7fbfa9bb07f5b6d5 to your computer and use it in GitHub Desktop.
Save LostinOrchid/e9baa780bebe24ea7fbfa9bb07f5b6d5 to your computer and use it in GitHub Desktop.
Warning on object assign mutation
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