What is the Object.assign() method in JavaScript?

Object.assign() is a method in JavaScript that is used to copy or merge objects.

Object.assign() performs a shallow copy; i.e., it only copies properties, not prototype methods.

Take a look at the function signature below:

The function signature
The function signature

Code

Copying an object

Object.assign() returns a target object.

let fruit = { name: 'Kiwi', price: 200 };
// Cloning fruit
let cloned_fruit = Object.assign({}, fruit);
console.log(cloned_fruit);
// Adding a property to the clone
let kiwi = Object.assign({weight: 500}, fruit);
console.log(kiwi);

​### Merging objects

In case of a name collision between a source and target property, Object.assign() will overwrite the local property of the target object.

let fruit = { name: 'Kiwi', price: 200 };
let details = {calories: 305, color: 'green'};
// Merging objects to create a new object
let kiwi = Object.assign({}, fruit, details);
console.log(kiwi);
// Observe that property calories exists in the source and target.
let kiwi2= Object.assign({calories : 100}, fruit, details);
console.log(kiwi2)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved