From f4cb058d7f969b8f3b14e4de6b29a1aced0c9f90 Mon Sep 17 00:00:00 2001 From: wonderingabout Date: Sun, 29 Mar 2020 08:05:46 +0200 Subject: [PATCH] trick get a new copy of objects/arrays using the spread operator --- .../02-rest-parameters-spread/article.md | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/1-js/06-advanced-functions/02-rest-parameters-spread/article.md b/1-js/06-advanced-functions/02-rest-parameters-spread/article.md index 74c85d4f..fad6dc5c 100644 --- a/1-js/06-advanced-functions/02-rest-parameters-spread/article.md +++ b/1-js/06-advanced-functions/02-rest-parameters-spread/article.md @@ -225,6 +225,51 @@ But there's a subtle difference between `Array.from(obj)` and `[...obj]`: So, for the task of turning something into an array, `Array.from` tends to be more universal. +## Get a new copy of an object/array + +Remember when we talked about `Object.assign()` [in the past](https://javascript.info/symbol#symbols-are-skipped-by-for-in)? + +It is possible to do the same thing with the spread operator! + +``` +let arr = [1, 2, 3]; +let arrCopy = [...arr]; // spread the array into a list of parameters + // then put the result into a new array + +// do the arrays have the same contents? +alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true + +// are the arrays equal? +alert(arr === arrCopy); // false (not same reference) + +// modifying our initial array does not modify the copy: +arr.push(4); +alert(arr); // 1, 2, 3, 4 +alert(arrCopy); // 1, 2, 3 +``` + +Note that it is possible to do the same thing to make a copy of an object: + +``` +let obj = { a: 1, b: 2, c: 3 }; +let objCopy = { ...obj }; // spread the object into a list of parameters + // then return the result in a new object + +// do the objects have the same contents? +alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true + +// are the objects equal? +alert(obj === objCopy); // false (not same reference) + +// modifying our initial object does not modify the copy: +obj.d = 4; +alert(JSON.stringify(obj)); // {"a":1,"b":2,"c":3,"d":4} +alert(JSON.stringify(objCopy)); // {"a":1,"b":2,"c":3} +``` + +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. + + ## Summary When we see `"..."` in the code, it is either rest parameters or the spread syntax.