Skip to content

JavaScript object Assign vs Spread

  • by

Both Object.assign() and the spread syntax (...) can be used to merge multiple objects into a single object in JavaScript.

Spread syntax

The spread syntax (...) can also be used to merge objects, but it creates a new object instead of modifying an existing one.

const result = { ...obj1, ...obj2 };

Object.assign() syntax

Object.assign() is a method that takes one or more source objects and copies their properties into a target object. It modifies the target object and returns it.

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

JavaScript object Assign vs Spread

FeatureObject.assign()Spread syntax
Merges objectsYesYes
Creates new objectNoYes
Modifies target objectYesNo
Returns merged objectYesYes
Works with arraysNoYes
Creates shallow copyNoYes

JavaScript object Assign vs Spread example

Simple example code.

<!DOCTYPE html>
<html>
  <body>
    <script>
    // Object.assign()
    const target = { a: 1, b: 2 };
    const source = { b: 4, c: 5 };
    const result = Object.assign(target, source);
    console.log(result); 

    // spread 
    const obj1 = { a: 1, b: 2 };
    const obj2 = { b: 4, c: 5 };
    const res = { ...obj1, ...obj2 };
    console.log(res); 

    </script>
  </body>
</html>

Output:

JavaScript object Assign vs Spread

Comment if you have any doubts or suggestions on this Js Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading