Skip to content

Commit c038ef4

Browse files
authored
Merge pull request #1823 from wonderingabout/trick-deep-copy-spread
Trick get a new copy of object/array using spread operator
2 parents ac5fd8c + f4cb058 commit c038ef4

File tree

1 file changed

+45
-0
lines changed
  • 1-js/06-advanced-functions/02-rest-parameters-spread

1 file changed

+45
-0
lines changed

1-js/06-advanced-functions/02-rest-parameters-spread/article.md

+45
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,51 @@ But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
225225
So, for the task of turning something into an array, `Array.from` tends to be more universal.
226226
227227
228+
## Get a new copy of an object/array
229+
230+
Remember when we talked about `Object.assign()` [in the past](https://javascript.info/symbol#symbols-are-skipped-by-for-in)?
231+
232+
It is possible to do the same thing with the spread operator!
233+
234+
```
235+
let arr = [1, 2, 3];
236+
let arrCopy = [...arr]; // spread the array into a list of parameters
237+
// then put the result into a new array
238+
239+
// do the arrays have the same contents?
240+
alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true
241+
242+
// are the arrays equal?
243+
alert(arr === arrCopy); // false (not same reference)
244+
245+
// modifying our initial array does not modify the copy:
246+
arr.push(4);
247+
alert(arr); // 1, 2, 3, 4
248+
alert(arrCopy); // 1, 2, 3
249+
```
250+
251+
Note that it is possible to do the same thing to make a copy of an object:
252+
253+
```
254+
let obj = { a: 1, b: 2, c: 3 };
255+
let objCopy = { ...obj }; // spread the object into a list of parameters
256+
// then return the result in a new object
257+
258+
// do the objects have the same contents?
259+
alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true
260+
261+
// are the objects equal?
262+
alert(obj === objCopy); // false (not same reference)
263+
264+
// modifying our initial object does not modify the copy:
265+
obj.d = 4;
266+
alert(JSON.stringify(obj)); // {"a":1,"b":2,"c":3,"d":4}
267+
alert(JSON.stringify(objCopy)); // {"a":1,"b":2,"c":3}
268+
```
269+
270+
This way of copying an object is much shorter than `let objCopy = Object.assign({}, obj);` or for an array `let arrCopy = Object.assign([], arr);` so we prefer to use it whenever we can.
271+
272+
228273
## Summary
229274
230275
When we see `"..."` in the code, it is either rest parameters or the spread syntax.

0 commit comments

Comments
 (0)