Codectionary / Developer documentation / JavaScript

Function Parameters: Default & Rest

Default parameters let you specify a fallback value used when an argument is omitted or undefined. Rest parameters, written with ...name, collect any remaining arguments into a real array, letting a function accept a variable number of arguments cleanly.

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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation