Techscrypt

ES6 spread operator

javascripttypescript

The ES6 spread operator does not make clones of objects. Rather, it keeps references to the original object as demonstrated in the code below:

var a = {
key1: 1,
key2: {
key3: 3,
},
};

var b = { ...a };
b.key2.key20 = 20;

console.log(b);
// {
// "key1": 1,
// "key2": {
// "key3": 3,
// "key20": 20
// }
// }

console.log(a);
// {
// "key1": 1,
// "key2": {
// "key3": 3,
// "key20": 20
// }
// }

var c = { one: 1, ...a };
c.key2.key10 = 10;

console.log(c);
// {
// "key1": 1,
// "key2": {
// "key3": 3,
// "key20": 20,
// "key100": 100
// },
// "one": 1
// }

console.log(a);
// {
// "key1": 1,
// "key2": {
// "key3": 3,
// "key20": 20,
// "key10": 10
// }
// }
console.log(a);
// {
// "key1": 1,
// "key2": {
// "key3": 3,
// "key20": 20,
// "key10": 10
// }
// }

So if you create a new object using the spread operator and modify nested properties on that object, you could modify the original object used in creation of the new object.

If the desired effect is to create a new object using an existing object, the best approach would be to use a library like lodash: for example clone the object using cloneDeep: https://lodash.com/docs#cloneDeep to create a clone of the object, and modify that object so as to not affect the original one.


Subscribe to the Newsletter

We will only use your email address to send out the weekly newsletter with the latest updates from Techscrypt.

* indicates required