Published Mar 28 2019
Introduced in ES2015
, this method copies all the enumerable own properties of one or more objects into another.
Its primary use case is to create a shallow copy of an object.
const copied = Object.assign({}, original)
Being a shallow copy, values are cloned, and objects references are copied (not the objects themselves), so if you edit an object property in the original object, thatβs modified also in the copied object, since the referenced inner object is the same:
const original = {
name: 'Fiesta',
car: {
color: 'blue'
}
}
const copied = Object.assign({}, original)
original.name = 'Focus'
original.car.color = 'yellow'
copied.name //Fiesta
copied.car.color //yellow
I mentioned βone or moreβ:
const wisePerson = {
isWise: true
}
const foolishPerson = {
isFoolish: true
}
const wiseAndFoolishPerson = Object.assign({}, wisePerson, foolishPerson)
console.log(wiseAndFoolishPerson) //{ isWise: true, isFoolish: true }
I wrote an entire book on this topic π
I also got a super cool course π
© 2023 Flavio Copes
using
Notion to Site
Interested in solopreneurship?