Skip to content

Instantly share code, notes, and snippets.

@MrAlexLau
Last active March 2, 2017 18:59
Show Gist options
  • Save MrAlexLau/7b7f32204610e02979941d9917647b9d to your computer and use it in GitHub Desktop.
Save MrAlexLau/7b7f32204610e02979941d9917647b9d 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