Default parameters
Give a parameter a default value with =. It is used when the argument is missing or undefined.
function greet(name = "stranger") {
return `Hello, ${name}!`;
}
console.log(greet("Maya")); // → Hello, Maya!
console.log(greet()); // → Hello, stranger!
console.log(greet(undefined)); // → Hello, stranger!
console.log(greet(null)); // → Hello, null!
Notice that only undefined triggers the default. null is a real value and is kept.
Defaults can use earlier parameters or any expression:
function box(width, height = width) {
return width * height;
}
console.log(box(5)); // → 25 (a square)
console.log(box(5, 2)); // → 10
Before ES2015, people wrote name = name || "stranger". Default parameters are clearer and do not mishandle 0 or "".
Rest parameters
A rest parameter ...name collects all remaining arguments into a real array.
function sum(...numbers) {
let total = 0;
for (const n of numbers) {
total += n;
}
return total;
}
console.log(sum(1, 2, 3)); // → 6
console.log(sum(10, 20)); // → 30
console.log(sum()); // → 0
It must be the last parameter. You can have normal parameters before it:
function log(level, ...messages) {
console.log(`[${level}]`, messages.join(" "));
}
log("info", "Server", "started"); // → [info] Server started
Rest vs spread
The same three dots ... do the opposite when you call a function: they spread an array out into separate arguments.
const scores = [3, 9, 5];
console.log(Math.max(...scores)); // → 9
- In a function definition,
...gathers arguments (rest). - In a function call or array/object literal,
...spreads them (spread).
See more in Spread Syntax for Arrays.
The old arguments object
Older code used a special arguments object. It is array-like but not a real array, and it does not exist in arrow functions. Rest parameters replace it.