Does spread operator create new object
In JavaScript, the spread operator (...
) does not create a new object. Instead, it creates a shallow copy of the original object.
When you use the spread operator to spread an object into a new object, it creates a new object with the same properties as the original object, but it does not create a new object with a new prototype chain.
Here's an example:
const original = { a: 1, b: 2 };
const copied = {...original };
console.log(copied); // { a: 1, b: 2 }
console.log(copied === original); // false (they are different objects)
As you can see, copied
is a new object with the same properties as original
, but it is not the same object.
If you want to create a deep copy of an object, you can use the JSON.parse(JSON.stringify(obj))
trick:
const original = { a: 1, b: { c: 3 } };
const copied = JSON.parse(JSON.stringify(original));
console.log(copied); // { a: 1, b: { c: 3 } }
console.log(copied === original); // false (they are different objects)
This creates a new object with a new prototype chain, which is a deep copy of the original object.
It's worth noting that the spread operator can also be used to merge objects, by spreading one object into another:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = {...obj1,...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }
In this case, the spread operator creates a new object with the properties from both obj1
and obj2
.