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):
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:
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:
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:
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?
Spreads an array into argumentsCollects the remaining arguments into an arrayMakes arguments optionalCopies the arguments object
Show answer
Answer: Collects the remaining arguments into an array