Script Valley
JavaScript: The Complete Language
Functions and ScopeLesson 2.4

Default parameters, rest parameters, and the spread operator

default parameters, rest parameters, spread operator, arguments object vs rest, spreading arrays, spreading objects, function arity, parameter destructuring

Modern Parameter Handling

ES6 introduced three features that make function signatures cleaner and more flexible. Together they replace most use cases that previously required the arguments object or manual fallback logic inside the function body.

Default Parameters

Assign a fallback value used when an argument is undefined or not provided at the call site.

function createUser(name, role = "viewer", active = true) {
  return { name, role, active };
}

createUser("Ana");           // { name: "Ana", role: "viewer", active: true }
createUser("Bob", "admin");  // { name: "Bob", role: "admin", active: true }

Rest Parameters

Collect all remaining arguments into a real Array. Must be the last parameter — no parameters may follow it.

function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10

Spread Operator

Expands an iterable into individual elements — the inverse of rest. Same ... syntax, opposite direction of data flow.

const nums = [3, 1, 4, 1, 5];
Math.max(...nums); // 5  — spread into individual args

const base = { theme: "dark" };
const config = { ...base, fontSize: 14 }; // shallow merge

const copy = [...nums]; // clone without mutation

Key Distinction

Rest collects into an array at the function definition. Spread expands out of an array at the call site or inside a literal. Remembering the direction of data flow prevents every common confusion between the two.

Up next

Higher-order functions: map, filter, reduce explained

Sign in to track progress