Home › Learn › JavaScript › Functions in depth

Default and rest parameters

Lesson 32 of 40. Optional parameters and any number of arguments.

A parameter with a default, function greet(name, greeting = "Hello"), can be left out by the caller. Defaults apply when the argument is undefined, including when it is simply missing. Parameters with defaults go after the required ones.

function sumAll(...nums) collects any number of arguments into an array called nums, the rest parameter. The same three dots spread an array into separate arguments when calling: Math.max(...nums). Functions also see an arguments object, but rest parameters are the modern way.

function repeat(text, times = 2, sep = " ") {
  return Array(times).fill(text).join(sep);
}
console.log(repeat("ho"));            // ho ho
console.log(repeat("ho", 3, "-"));    // ho-ho-ho
const biggest = (...nums) => Math.max(...nums);

Your task

Write greet(name, greeting = "Hello", punctuation = "!") returning "<greeting>, <name><punctuation>", average(...nums) returning the mean or 0 when called with nothing, and joinWords(separator, ...words) joining the words with the separator.

Hint 1

function greet(name, greeting = "Hello", punctuation = "!") { return `${greeting}, ${name}${punctuation}`; }

Hint 2

function average(...nums) { if (nums.length === 0) return 0; return nums.reduce((a, b) => a + b, 0) / nums.length; }

Show the solution
function greet(name, greeting = "Hello", punctuation = "!") {
  return `${greeting}, ${name}${punctuation}`;
}

function average(...nums) {
  if (nums.length === 0) return 0;
  return nums.reduce((a, b) => a + b, 0) / nums.length;
}

function joinWords(separator, ...words) {
  return words.join(separator);
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.