The spread and rest operators help deal with iterables and arrays in an easy manner. They are defined by the three dots (...)
. Let’s take a look and see how and when to use each.
Spread Operator
Let’s say we want to copy an array to another array. We can do this in two ways:
Classical way to copy an array:
const array = [1,3,5,7];
const newArray = [];
for (const index in newArray) {
newArray[index] = array[index];
}
Using the spread operator:
The spread operator makes this operation much easier:
const array = [1,3,5,7];
const newArray = [...array]; //[1,3,5,7]
What happened in the second example is that the spread operator was used to expand the values contained in the original array into the new array and the values were copied. There are two things that we must be aware of:
-
The original data structure (arrays, objects, etc.) remains unaltered.
-
If you add any new values to the original data structure, the new data structure will not automatically receive the new values and vice versa.
array.push(9);
console.log(array); //1,3,5,7,9
console.log(newArray); //1,3,5,7
newArray.push(11);
console.log(array); //1,3,5,7,9
console.log(newArray); //1,3,5,7,11
We can also copy multiple arrays into a new array using the spread operator:
const numbers = [1,2,3,4];
const numbers1 = [5,6,7,8];
const newNumbers = [...numbers, ...numbers1]; //[1,2,3,4,5,6,7,8]
The spread operator is not limited to copying arrays. It can also be used to copy objects:
const obj = {a: 1, b: 2, c: 3};
const newObj = {...obj}; //{a: 1, b: 2, c: 3}
Prior to the spread operator, there was the apply function, which allowed you to use the values in an array and pass them as arguments to a function:
const arguments = [1,2,3,4];
function fun(a, b, c, d){}
fun.apply(null, arguments);
Rest Operator
As stated previously, the rest operator uses the same three dots (...)
as the spread operator, but the spread operator is used in expanding the values contained in an array, for example, while the rest operator is used in gathering values into an array.
When using the rest operator in a function’s parameter list, it must come as the last parameter. Otherwise, you will get an error:
function(a, ...b, c){} //WRONG //SyntaxError: Rest parameter must be last formal parameter
function(a, b, ...c){} //RIGHT
The rest operator can also be used with destructuring:
const evenNumbers = [2,4,6,8];
[first, second, ...restOfArray] = evenNumbers;
console.log(first); //2
console.log(second); //4
console.log(restOfArray) //[6,8]
You can even skip elements in arrays:
const evenNumbers = [2,4,6,8];
[first, , ...restOfArray] = evenNumbers;
console.log(first); //2
console.log(restOfArray) //[6,8]
const evenNumbers = [2,4,6,8];
[first, ,, ...restOfArray] = evenNumbers;
console.log(first); //2
console.log(restOfArray) //[8]