Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

objects
methods
javascript

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

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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:

svg viewer
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)

RELATED TAGS

objects
methods
javascript
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring