Any Number of Values
A birthday invitation says: "Bring anyone you like". One guest comes alone, another one comes with three friends. The host doesn't need to know the number before: they just open the door to everyone who comes. Some functions are like that host.
Any number of values
console.log takes one value, two, ten: console.log("a", "b", "c"). Your own functions until now take a fixed number of parameters. To take any number, write three dots before the last parameter:
function greetAll(...names) {
console.log(names);
}
greetAll("Mia", "Ben", "Ana");
greetAll("Dan");
greetAll();
[Mia, Ben, Ana]
[Dan]
[]
...names is a rest parameter: it collects all the rest of the values into an array. Nothing given? It's an empty array, never undefined. Other parameters can come before it: function invite(host, ...guests).
Spread or rest?
The same three dots have two jobs:
- In a call, they spread an array into separate values:
greetAll(...pupils). - In a parameter, they collect separate values into an array:
function greetAll(...names).
So when your names are already in an array, spread it into the call:
const pupils = ["Mia", "Ben"];
greetAll(...pupils);
Break it on purpose
Call greetAll(pupils) without the dots. names is an array with one item, which is itself the whole array: [[Mia, Ben]]. Then write the function as function greetAll(names) without dots, and call greetAll("Mia", "Ben"). names is only "Mia", and "Ben" is lost.
Mission: Docked now
What you will see: under the closest starships, a line:
Docked now: Aurora, Silver Gull
When no starship is docked, it says Docked now: none.
The crew wants one line that names every starship docked at the station right now.
- In
tracker.js, a functionlistNamestakes any number of names. - It returns them joined with
,, ornonewhen it got no name at all. - Between
#closestand the listships, add a paragraph with the iddocked-now. - When the starships are in,
loadShipswrites in itDocked now:, then whatlistNamesgives for the names of the docked starships. - Those names are spread into the call.
The dots in the parameter collect, and the dots in the call spread.