Three useful dots – the rest and the spread in JavaScript
Lukasz Kolko
ECMAScript 2015 brought us a lot of news, which resulted in a large number of improvements. Today we will take a closer look at two features that make life easier. Meet the rest paremeters and the spread syntax.
The spread operator allows us to expand iterable objects into individual elements. This functionality is opposite to what we achieved with the rest parameters. It can be applied to all iterables, such as arrays, objects, sets, maps, etc.
const sum = (x, y, z) => x + y + z;
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
Notice that spread syntax creates ‘shallow’ copy of the object, so ‘wallet’ property will be copied only as a reference to the original sub-object. For deep-cloning you can use JSON stringify/parse approach or ‘cloneDeep’ method provided by Lodash depending on your object’s complexity. In some cases this method can be helpful as well:
let personCopy = { ...person, wallet = {...person.wallet}};