JavaScript Object.assign() Method

The Object.assign function serves the purpose of duplicating the values of all enumerable own properties from one or several source objects to a designated target object. It is important to note that objects are assigned and replicated by reference. The method will return the target object after the operation.

Syntax:

Example

Object.assign(target, sources)

Parameter

target : The target object.

sources : The source object(s).

Return value:

This method returns the target object.

Browser Support:

Chrome Yes
Edge Yes
Firefox Yes
Opera No

Example 1

Example

const object1 = {

  a: 1,

  b: 2,

  c: 3

};

const object3= {

  g: 1,

  h: 2,

  i: 3

};	



const object2 = Object.assign({c: 4, d: 5}, object1);

const object4 = Object.assign({g: 34, h: 25}, object3);

console.log(object2.c, object2.d);

console.log(object4.g, object4.h);

Output:

Output

3 

5

1 

2

Example 2

Example

const object1 = {

  a: 11,

  b: 12,

  c: 33

};



const object2 = Object.assign({c: 4, d: 5}, object1);

console.log(object2.c, object2.d);

Output:

Output

33 

5

Example 3

Example

const object1 = {

  a: 1,

  b: 2,

  c: 3

};



const object2 = Object.assign({a: 3,c: 4, d: 5,g: 23,}, object1);



console.log(object2.c, object2.d,object2.g,object2.a);

Output:

Output

3 

5 

23 

1

Input Required

This code uses input(). Please provide values below: