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
Feature | Object.assign() | Spread syntax |
---|---|---|
Merges objects | Yes | Yes |
Creates new object | No | Yes |
Modifies target object | Yes | No |
Returns merged object | Yes | Yes |
Works with arrays | No | Yes |
Creates shallow copy | No | Yes |
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:
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