JavaScript Object.assign() Method

JavaScript Object.assign() Method | The values of all enumerable own properties are copied from one or more source objects to a target object using the Object.assign() function. By reference, objects are assigned and copied. It will deliver the desired object back.

The values and properties of one or more source objects are copied to a destination object using the Object.assign() function. Since it utilizes [[Get]] on the source and [[Set]] on the destination, it employs getters and setters. It gives back the target object with copied values and properties from the source object. When the source value is null or undefined, Object.assign() does not fail.

Syntax:- Object.assign(target, … sources)

Return Value: Object.assign() returns the target object.
Parameters accepted by Object.assign() method:-

  • target: It is the target object to which values and properties have to be copied.
  • sources: It is the source object from which values and properties have to be copied.
const object1 = {
  a: 1,
  b: 2,
  c: 3,
};

const object3 = {
  g: 1,
  h: 2,
  i: 3,
};

const object2 = Object.assign({ c: 6, d: 7 }, object1);
const object4 = Object.assign({ g: 45, h: 67 }, object3);

console.log(object2);
console.log(object4);
console.log(object2.c, object2.d);
console.log(object4.g, object4.h);

object2.c = 10;
object4.g = 90;

console.log(object2);
console.log(object4);

Output:-

{ c: 3, d: 7, a: 1, b: 2 }
{ g: 1, h: 2, i: 3 }
3 7
1 2
{ c: 10, d: 7, a: 1, b: 2 }
{ g: 90, h: 2, i: 3 }

const object1 = {
  a: 1,
  b: 2,
  c: 3,
};

const object2 = Object.assign({ c: 10, d: 12 }, object1);
console.log(object2.c, object2.d);

Output:-

3 12

We can also use Object.assign() method to merge two objects together. See more:- JavaScript Merge Objects

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  ssn: "123-456-4741",
};

let job = {
  jobTitle: "JavaScript Developer",
  country: "USA",
};

let employee = Object.assign(person, job);
console.log(employee);

Output:-

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  ssn: '123-456-4741',
  jobTitle: 'JavaScript Developer',
  country: 'USA'
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *