Rest Operator Javascript

Yoel Macia
2 min readDec 1, 2019

--

After a series of Spread Operator (Arrays and Objects).

Today we are going to talk about the Rest Operator, unlike the spread operator, collects all the remaining elements in a matrix.

Photo by Jan Phoenix on Unsplash

For example we have this function,

const multiply = (a, b) => {
return a * b;
}
multiply(1,2) // 2

So far so good, but what happens when we pass more arguments than accept the function.

multiply(1,2,3), the result will always be 2 because in Javascript we can call functions with the elements we want but in this case will only count the first two elements.

Here comes into the game our friend the Rest Operator.

We can rewrite the previous function as,

const multiply = (...args) => {
let result = 1;
for (let i in args) {
result = result * args[i];
}
return result;
};

And now we can pass on all the arguments we want.

multiply(1,2) // 2
multiply(2,2,2) // 8
multiply(3,2,1,2) // 12

But we have limitations of use, if we have a function with more arguments, the Rest Operator always has to go in last position for example.

const multiply = (x,y,...args) => {
console.log(x);
console.log(y);
let result = 1;
for (let i in args) {
result = result * args[i];
}
return result;
};
multiply(2,2,2) // 2 2 4
multiply(2,2,2,2) // 2 2 8

Thank you very much and keep coding!!!

Yoel

I often share more code tips on my Instagram you can say hello to me on my Twitter or see how i code in my Github.

--

--

Yoel Macia

Writing daily about Javascript. Creator of the publication The Javascript Adventure.