π What is Object.assign
normally it is used when merge multiple objects
const target = {city: 'japan', capital: 'tokyo'} const source = {food: 'sushi', history: 'samurai'} const result = Object.assign(target, source) console.log(target) /** { city: 'japan', capital: 'tokyo', food: 'sushi', history: 'samurai' } **/ console.log(source) // {food: 'sushi', history: 'samurai'} console.log(result) /** { city: 'japan', capital: 'tokyo', food: 'sushi', history: 'samurai' } **/
π Object.assign in real life
Contrary to this way of merge, according to my experience, it's often used when wants to copy object
let animal = {name: 'pikachu', type: 'kawaii'} let copy_animal = Object.assign({}, animal) console.log(copy_animal) // {name: 'pikachu', type: 'kawaii'}
π₯ Warning (reference)
Now give you a quiz, is this true or false ??
animal === copy_animal
γ»
γ»
γ»
The answer is false
βΌ proof
βΌ There is my other article, which explains about it.

{} === {} is false... π³WHaT?? Let me explain it with image πΌ
Kaziu γ» Sep 22 '22
π₯ Warning2 (shallow copy)
let animal = {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'} copy_animal = Object.assign({}, animal) // change value copy_animal.type = 'dirty' console.log(animal) // {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'} // β still pikachu is kawaii !!
Because these objects are on different references
BUT
// change value of second hierarchy copy_animal.name.last = 'suzuki' console.log(animal) // {name: {first: 'pikachu', last: 'suzuki'}, type: 'kawaii'} // β changed 'honda' => 'suzuki' !!!!!!!!!!!
π How this result come ?? You said these objects are on different references !!
Yup, but actually this is only 1 hierarchy of object, over 2 hierarchy objects are on same reference and this is called Shallow copy
Yup Object.assign is shallow copy
π Spread operator
By the way spread operator is the same as Object.assign
let animal = {name: 'pikachu', type: 'kawaii'} let copy_animal = {...animal} console.log(copy_animal) // {name: 'pikachu', type: 'kawaii'}
But also shallow copy !!!!!
Top comments (0)