Copy objects with Object.assign() in JavaScript

The Object.assign() method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'set' on the target.

Syntax

Object.assign(target, ...sourceObjects);

The first parameter is the target object that will be modified and returned. The remaining parameters are source objects whose properties will be copied to the target.

Basic Example

const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };

const result = Object.assign(target, source);

console.log("Target after assignment:", target);
console.log("Returned result:", result);
console.log("Are target and result the same?", target === result);
Target after assignment: { a: 1, b: 3, c: 4 }
Returned result: { a: 1, b: 3, c: 4 }
Are target and result the same? true

Creating a New Copy

To avoid modifying the original object, use an empty object as the target:

const original = { name: "John", age: 30 };
const copy = Object.assign({}, original);

copy.age = 35;

console.log("Original:", original);
console.log("Copy:", copy);
Original: { name: 'John', age: 30 }
Copy: { name: 'John', age: 35 }

Copying Functions

const object = { first: second => second + 1000 };
const object2 = Object.assign({}, object);

console.log("The result =", object2.first(1000));
The result = 2000

Multiple Source Objects

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };

const merged = Object.assign({}, obj1, obj2, obj3);

console.log("Merged object:", merged);
Merged object: { a: 1, b: 2, c: 3 }

Property Overwriting

When properties have the same name, later sources overwrite earlier ones:

const obj1 = { a: 1, b: 1, c: 1 };
const obj2 = { b: 2, c: 2 };
const obj3 = { c: 3 };

const result = Object.assign({}, obj1, obj2, obj3);

console.log("Result:", result);
Result: { a: 1, b: 2, c: 3 }

Key Points

  • Object.assign() performs a shallow copy only
  • The target object is modified and returned
  • Only enumerable own properties are copied
  • Properties are overwritten if they exist in multiple sources

Conclusion

Object.assign() is useful for copying and merging objects. Remember it creates shallow copies, so nested objects are still referenced, not copied.

Updated on: 2026-03-15T23:18:59+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements