
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use of Object.assign in JavaScript
The Object.assign() method is used to copy the values of all of the object's own properties(enumerable only) from one or more source objects to a target object. It will return the target object.
Example
const targetObj = { a: 1, b: 2 }; const sourceObj = { b: 4, c: 5 }; const returnedTarget = Object.assign(targetObj, sourceObj); console.log(targetObj); console.log(returnedTarget); console.log(returnedTarget === targetObj); console.log(sourceObj);
Output
{ a: 1, b: 4, c: 5 } { a: 1, b: 4, c: 5 } true { b: 4, c: 5 }
Note −
sourceObj did not change.
returnedTarget and targetObj are the same.
The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters.
Advertisements