How to create a shallo wcopy of an object with `Object.assign()`?

let sourceObj = { firstname: 'Hans', lastname: 'Meyer' }

// copy all properties of `sourceObj` into an empty object `{}`
let copyObj = Object.assign({}, sourceObj);

// output: { firstname: 'Hans', lastname: 'Meyer' }
console.log(copyObj)

// copy all properties of `sourceObj` into `targetObj`
let targetObj = { occupation: 'Developer' }

// returns { occupation: 'Developer', firstname: 'Hans', lastname: 'Meyer' }
Object.assign(targetObj, sourceObj);
Copy

April 12th, 2020

# Object.assign() - Shallow copy of an object

Add to bookmarks

Object.assign() copies the top level properties of an object to create a copy. It fails when the object contains nested objects as properties.

The Object.assign() method expect two parameters: The target as first and the source as second parameter. Multiple sources can be assigned.

Important: We can't copy an object by doing let newObj = obj because this will only create a reference to the same object. This is because the variable obj contains the pointer to place in memory, which holds the value of the object.

HomeBookmarks