Skip to main content
eLearner.app
Module 4 · Lesson 3 of 415/32 in the course~12 min
Module lessons (3/4)

Default and rest parameters

JavaScript lets you make parameters optional (with a default value) and accept a variable number of arguments with the rest operator (...).

Default parameters

JS
function saluta(nome, prefisso = 'Ciao') {
  return `${prefisso}, ${nome}!`;
}

saluta('Anna'); // 'Ciao, Anna!'
saluta('Marco', 'Buongiorno'); // 'Buongiorno, Marco!'

The default applies only when the argument is undefined (including the "not passed" case). For null or 0 the default does not kick in:

JS
function f(x = 10) {
  return x;
}
f(); // 10
f(undefined); // 10
f(null); // null
f(0); // 0

Rest: ...names

To accept a variable number of arguments, collect them into an array with ...:

JS
function somma(...numeri) {
  let totale = 0;
  for (const n of numeri) totale += n;
  return totale;
}

somma(); // 0
somma(5); // 5
somma(1, 2, 3, 4); // 10

Inside the function, numeri is a real array (not the magic arguments object of old functions).

The rest must be the last parameter:

JS
function f(primo, ...altri) {
  /* ok */
}
// function f(...altri, ultimo) {} // SyntaxError

Spread at call time

The other face of ... is the spread operator, which "explodes" an array into separate arguments at call time:

JS
function somma(a, b, c) {
  return a + b + c;
}

const nums = [1, 2, 3];
somma(...nums); // 6, equivalent to somma(1, 2, 3)

Try it

Exercise#js.m4.l3.e1
Attempts: 0Loading…

Define a function `sum(a, b)` where `b` has a default value of 0. It must pass these asserts: sum(5) === 5, sum(2, 3) === 5, sum(0) === 0.

Loading editor…
Show hint

function sum(a, b = 0) { return a + b; }

Solution available after 3 attempts

Review exercise

Exercise#js.m4.l3.e2
Attempts: 0Loading…

Define a function `mean(...nums)` that returns the arithmetic mean of its arguments, or 0 if none are passed.

Loading editor…
Show hint

If nums.length is 0, return 0; otherwise sum and divide.

Solution available after 3 attempts