JavaScript Tutorial · Functions · Lesson 20 of 44

JavaScript Parameters

Default values, rest parameters and the spread operator.

Default parameters

Give a parameter a default value that's used when the argument is missing (or undefined):

Example 1Try it yourself
function greet(name = "friend", greeting = "Hello") {
  return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet("Ada"));
console.log(greet("Ada", "Welcome"));

Output

Hello, friend!
Hello, Ada!
Welcome, Ada!

Rest parameters

...name as the last parameter collects any remaining arguments into an array:

Example 2Try it yourself
function sum(...numbers) {
  let total = 0;
  for (const n of numbers) total += n;
  return total;
}
console.log(sum(1, 2), sum(1, 2, 3, 4), sum());

Output

3 10 0

Spread arguments

The same ... syntax used when calling spreads an array into separate arguments:

Example 3Try it yourself
const scores = [71, 94, 88];
console.log(Math.max(...scores));
console.log(Math.min(...scores, 50));

Output

94
50

Named options

For functions with many optional settings, accept one object and destructure it — calls become self-documenting:

Example 4Try it yourself
function createButton({ label, color = "blue", disabled = false } = {}) {
  return `<button class="${color}"${disabled ? " disabled" : ""}>${label}</button>`;
}
console.log(createButton({ label: "Save" }));
console.log(createButton({ label: "Delete", color: "red", disabled: true }));

Output

<button class="blue">Save</button>
<button class="red" disabled>Delete</button>

Test yourself

What does ...args in a function's parameter list do?

  1. Spreads an array into arguments
  2. Collects the remaining arguments into an array
  3. Makes arguments optional
  4. Copies the arguments object
Show answer

Answer: Collects the remaining arguments into an array