-
-
Save hoorayimhelping/82c708d81029e7d98ac28f8853b5fc97 to your computer and use it in GitHub Desktop.
object.assign vs the spread operator
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
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