Member-only story

JavaScript Rest Operator

What good is it?

Rich Brown
3 min readMay 24, 2021
Photo by Mika Baumeister on Unsplash

The rest operator was released with JavaScript version ES6 which was released in 2015 and used in most modern browsers.

The main use of the rest operator is in function arguments. Let’s look at the this example:

“use strict” // Always usefunction sum( a, b ) {
return a + b;
}
sum(1, 2); // 3sum(1, 2, 3, 4); // 3sum(1); // NaN

In the first call to sum, sum(1,3), it returns 3 as expected, but in the second call, sum(1,2,3,4), it also returns 3 just ignoring the extra arguments.

All JavaScript functions all contain a property called arguments. In this line, the function is like this:

function sum(a, b){
// arguments = [1, 2, 3, 4]
// a = 1, b = 2 — the other values are ignored
return a + b;
}
sum(1, 2, 3, 4); // 3

In the third call, sum(1), it returns NaN, not a number. It attempts to add the value of a, 1, to the undefined value of b which returns NaN.

function sum(a, b){
// arguments = [1]
// a = 1
return a + b;
}
sum(1); // NaN

--

--

Rich Brown
Rich Brown

Written by Rich Brown

Passionate about using AI to enhance daily living, boost productivity, and unleash creativity. Contact: richbrowndigital@gmail.com

No responses yet