JavaScript Object.assign() Method - JavaScript Tutorial

JavaScript Object.assign() Method

BLUF: This tutorial on JavaScript Object.assign() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Object.assign() Method

Understanding JavaScript Object.assign() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience