The JavaScript spread operator (...
) is a powerful feature introduced in ES6 (ECMAScript 2015) that allows you to expand elements from an iterable (like an array or an object) into another iterable or as function arguments. When used with objects, it enables you to create copies of objects and combine them with new properties or modify existing ones.
When it comes to copying objects and their properties, the spread operator is commonly used to create shallow copies. Let’s explore how it works and its effects:
However, keep in mind that the spread operator creates a shallow copy. If the object contains nested objects, those nested objects will still be shared between the original and the copied object:
Lets take an example
2So we get the same value for ‘twitter’ for both, which is a bug. In order to fix it, lets rewrite it in below way
Now we get the desired output.
const myFriendd = { ...mee, socials: { ...mee.socials } };
Here, a new object named myFriendd
is created using the spread syntax (...
). This creates a shallow copy of the mee
object. The socials
property is also copied using the spread syntax to ensure that changes made to myFriendd.socials
don’t affect mee.socials
.
full source code here
Happy coding… !
Leave a comment