Skip to content

Instantly share code, notes, and snippets.

@hoorayimhelping
Forked from MrAlexLau/object assign
Created March 2, 2017 18:59
Show Gist options
  • Save hoorayimhelping/82c708d81029e7d98ac28f8853b5fc97 to your computer and use it in GitHub Desktop.
Save hoorayimhelping/82c708d81029e7d98ac28f8853b5fc97 to your computer and use it in GitHub Desktop.
object.assign vs the spread operator
const a = { foo: 'foo'};
const b = { bar: 'bar'};
// the wrong way
const result = Object.assign(a, b);
console.log(a)
// { foo: 'foo', bar: 'bar' }
// this is usually bad, we usually don't want to mutate `a` in most cases
// The right ways:
// 1. using Object.assign with an empty hash for the first param:
const result = Object.assign({}, a, b);
console.log(a)
// { foo: 'foo' }
// 2. using the spread operator
const result = {
foo: 'foo',
...b
};
// or
const result = {
...a,
...b
};
console.log(a)
// { foo: 'foo' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment