Syntax
function name(param = defaultValue, ...rest) { }Examples
Default Parameters
Providing fallback values for missing arguments.
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
greet(); // "Hello, Guest!"
greet("Alice"); // "Hello, Alice!"
greet("Bob", "Hi"); // "Hi, Bob!"Rest Parameters
Collecting a variable number of arguments into an array.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
function logDetails(name, ...tags) {
console.log(name, "->", tags);
}
logDetails("Article", "js", "tutorial", "web"); // "Article -> [js, tutorial, web]"Best practices
- Place rest parameters last in the parameter list - they must be, since they collect everything remaining
- Prefer default parameters over manually checking `if (param === undefined)` inside the function body
- Use rest parameters instead of the old `arguments` object for a real array with all standard array methods available
- Keep the number of parameters manageable - beyond 3-4, consider accepting a single options object instead
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification