Collecting Arguments With Rest Parameters

Every climber at the desk now gets a wristband from their own session’s counter. Next comes the bill. Ana Reyes pays for a day pass and shoe hire, Ben Okafor only a concession pass, and a chalk bag adds a third charge, so the desk script’s bill() takes any number of charges.

In Python, that’s a job for *args. JavaScript has its own way to collect arguments. But a call that Python refuses outright produces a wrong total in JavaScript without an error.

Collect the Charges Into an Array

The Python version gathers whatever it’s given into charges and adds it up:

Language: Python
def bill(*charges):
    return sum(charges)

print(bill(14, 4))
print(bill())

Python prints 18 for Ana and 0 for a call with no charges. In the JavaScript port, three dots before the parameter name do the collecting:

Language: JavaScript
function bill(...charges) {
  return charges.reduce((total, charge) => total + charge, 0);
}

console.log(bill(14, 4));
console.log(bill());

Run it, and you get the same two totals:

Language: Program Output
18
0

...charges is a rest parameter, which collects the rest of the arguments into one array. Where Python’s *charges gives you a tuple, JavaScript gives you an ordinary array, empty when nothing is passed, so .reduce() and the other array methods work on it.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.