💎 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
#javascript
#beginners
🔥 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 !!!!!