How code is written today

INPUT · Slides

Arguments that catch any number

01 / 05

Sometimes the number of arguments is not settled

When you make a function that produces a total, how many numbers you add is not necessarily settled in advance.

Write function total(a, b, c) and it becomes a three-only affair. Call it with two and the missing one becomes undefined; call it with four and the fourth gets ignored.

function total(a, b, c) {  return a + b + c;}console.log(total(1, 2));

Result

NaN

02 / 05

Write ... on the catching side

Write ... in front of an argument name and it catches everything handed over, gathered together. This way of writing is called rest parameters — "all the rest".

What you catch is an array. So .length and forEach work on it as they are.

function collect(...numbers) {  console.log(numbers);}collect(1, 2, 3);

Result

[1, 2, 3]

03 / 05

Handle it as an array

Inside it is an array, so you can run a for over it as always. However many are handed over, the same code adds them.

Call it with a different number and the function needs no line changed. You no longer have to mind the count.

function total(...numbers) {  let sum = 0;  for (let i = 0; i < numbers.length; i++) {    sum += numbers[i];  }  return sum;}console.log(total(10, 20));console.log(total(1, 2, 3, 4));

Result

30
10

04 / 05

Spread out, and gather up

The same ... and yet it looks like it has two meanings. In fact one way of remembering does.

  • written on the value side, it spreads[...fruits, "peach"]
  • written on the catching side, it gathersfunction total(...numbers)

Loosening things out, or bundling them up. Remember that where you write it decides the direction.

function collect(...numbers) {  return numbers;}const nums = [1, 2];console.log([...nums, 3]);console.log(collect(1, 2, 3));

Result

[1, 2, 3]
[1, 2, 3]

05 / 05

Combine it with ordinary arguments

Mixing it with ordinary arguments is fine. They are handed out from the front, and all the leftovers go into the ... one.

But ... can only be written right at the end. It is "the rest", so no argument can sit behind it.

Right — let us make a function that catches any number.

function introduce(name, ...likes) {  console.log(name);  console.log(likes);}introduce("Yui", "apple", "orange");

Result

Yui
["apple", "orange"]