Collecting Arguments With Rest Parameters

Every climber now has a wristband, so next comes the bill. The Python desk script totals any number of charges with def bill(*charges) and sum(charges). JavaScript collects arguments much the same way, but one call that Python refuses gives Ana a wrong total, with no error.

Collect the Charges Into an Array

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());

Ana’s day pass and shoe hire come to 18, and passing no charges gives 0:

Language: Program Output
18
0

...charges is a rest parameter: an ordinary array where Python gives you a tuple, empty when nothing is passed. JavaScript has no built-in sum() function like Python’s, so .reduce() carries a running total through the charges starting at 0. Watch out for the Python star, because *charges in a parameter list or a call stops the file with SyntaxError: Unexpected token '*'.

Rest parameters replace arguments, which older code may use. It’s an object containing every argument a non-arrow function receives, with .length but no array methods.

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.