The assign() method of the object

Find out all the information about the JavaScript Assign() method of the Object object

IntroducingES2015, This method will copy allUncountable own propertyOne or more objects become another.

Its main use case is to create shallow copies of objects.

const copied = Object.assign({}, original)

As a shallow copy, the value will be cloned and the object reference (not the object itself) will be cloned, so if you edit the object properties in the original object, it will also be modified in the copied object because the referenced internal object is the same of:

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 }

Download mine for freeJavaScript beginner's manual


More js tutorials: