ES6+ Spread Operator
In ES6+ JavaScript the 3 dots ...
can be used in two ways: as a spread operator, or as a rest parameter. In this post I’m going to be breaking down the spread operator.
One of the more useful features of ES6, it allows iterables (arrays / objects) to be expanded into their individual values.
Spreading Arrays
Combine arrays
The spread operator allows you to easily combine two (or more) arrays.
const array1 = [1,2,3];
// [1,2,3,4,5,6]
const combined = [...array1, 4,5,6];
You can also use it more than once…
const array1 = [1,2,3];
const array2 = [4,5,6];
// [1,2,3,4,5,6]
const combined = [...array1, ...array2];
Copying an array
Arrays in JS are references, if you try and copy one with = you’ll only copy a reference to the original array – not the actual values.
In this example, I copy array1 and then push a new value. Because array2 is just a reference – it’ll log the same updated value.
const array1 = [1,2,3];
const array2 = array1;
array1.push(4);
// [1,2,3,4]
console.log(array2);
With the spread operator – array2 is a totally separate array with its own values.
const array1 = [1,2,3];
const array2 = [...array1];
array1.push(4);
// [1,2,3]
console.log(array2);
Math functions
Some functions (like the Math object) expect a list of arguments, they’ll fail if you pass them an array.
Since the spread operator expands into a list of values, you can use it instead.
const array1 = [4,5,6];
// NaN
const nope = Math.min(array1);
// 4
const min = Math.min(...array1);
Spreading Objects
Note
Spreading properties for objects are actually ES2018 (ES9) rather than ES6.
Copying an object
Just like arrays, JS objects are references.
const object1 = { lorem: 1 };
const object2 = object1;
object1.ipsum = 2;
// { lorem: 1, ipsum: 2 }
console.log(object2);
Once again the spread operator creates a brand new object rather than just a reference.
const object1 = { lorem: 1 };
const object2 = {...object1};
object1.ipsum = 2;
// { lorem: 1 }
console.log(object2);
Combining objects
const object1 = {
lorem: 1,
};
// { lorem: 1, ipsum: 2 }
const combined = {...object1, ipsum: 2};
You can use any number of spread operators.
const object1 = {
lorem: 1,
};
const object2 = {
ipsum: 2,
}
// { lorem: 1, ipsum: 2 }
const combined = {...object1, ...object2};