.assign()
Published Dec 4, 2023
Contribute to Docs
The Object.assign()
method is used to modify a “destination” object with the contents of one or more objects passed to the method. If there are duplicate keys between the objects the values in the destination object will be overridden in the assignment.
Syntax
Object.assign(destinationObj, sourceObj)
// Or
Object.assign(destinationObj, sourceObj, ... nObj)
destinationObj
: The object to be modified. The entries of the other objects passed will be added to this object.sourceObj
: The object(s) that will be used to supplement the “destination” object.
Example
The following code demonstrates a basic implementation of the Object.assign()
method:
const eastLibrary = {1: 'Green Eggs and Ham',2: 'Cat in the Hat',3: 'Hop on Pop',};const westLibrary = {3: 'Lorax',4: 'How the Grinch Stole Christmas',5: 'The Zax',};const seussBooks = Object.assign(eastLibrary, westLibrary);console.log(seussBooks);
This will return the following output:
{'1': 'Green Eggs and Ham','2': 'Cat in the Hat','3': 'Lorax','4': 'How the Grinch Stole Christmas','5': 'The Zax'}
Note: The reassignment in the code above is optional. The following is true:
eastLibrary === suessBooks
.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Skill path
Create a Back-End App with JavaScript
Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.Includes 8 CoursesWith CertificateBeginner Friendly30 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours