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
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:
function f(x = 10) {
return x;
}
f(); // 10
f(undefined); // 10
f(null); // null
f(0); // 0Rest: ...names
To accept a variable number of arguments, collect them into an array with ...:
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); // 10Inside the function, numeri is a real array (not the magic arguments object of old functions).
The rest must be the last parameter:
function f(primo, ...altri) {
/* ok */
}
// function f(...altri, ultimo) {} // SyntaxErrorSpread at call time
The other face of ... is the spread operator, which "explodes" an array into separate arguments at call time:
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
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.
Show hint
function sum(a, b = 0) { return a + b; }
Solution available after 3 attempts
Review exercise
Define a function `mean(...nums)` that returns the arithmetic mean of its arguments, or 0 if none are passed.
Show hint
If nums.length is 0, return 0; otherwise sum and divide.
Solution available after 3 attempts