JavaScript Function Parameters: Defaults, Rest Parameters, arguments, Spread and Destructuring
How arguments reach parameters in JavaScript: missing and extra arguments, default values (and when they apply), rest parameters, the legacy arguments object, spreading arrays into calls, destructured "named" parameters with defaults, pass-by-sharing, and validating argument types.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript is relaxed about function arguments: it doesn't check their types or even their number. That flexibility is convenient, but it means you need to understand exactly what happens when callers pass too few, too many or the wrong kind of arguments. This article covers every tool for handling parameters well.
Arguments are matched by position
When you call a function, the first argument goes to the first parameter, the second to the second, and so on. Missing arguments leave their parameters undefined; extra arguments are ignored (though still available, as we'll see):
function greet(name, greeting) {
return `${greeting} ${name}`;
}
console.log(greet("Ana")); // greeting is undefined
console.log(greet("Ana", "Hi", "ignored"));
undefined Ana
Hi Ana
No error in either case. That's why the tools below exist: to give missing parameters sensible values and to collect extra arguments deliberately.
![For function order(item, qty = 1, ...notes): the call order("tea", 3, "hot", "no sugar") sets item to "tea", qty to 3 and notes to ["hot", "no sugar"]; the call order("tea") sets item to "tea", qty to its default 1 and notes to an empty array](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-function-parameter-matching-g3gu7rhuqdv56hwt.png)
Default parameter values
Write = value after a parameter to give it a default (ES2015):
function welcome(name, greeting = "Hello") {
return `${greeting}, ${name}`;
}
console.log(welcome("Bo"));
console.log(welcome("Bo", undefined)); // undefined: default used
console.log(welcome("Bo", null)); // null is a real value: no default
console.log(welcome("Bo", "")); // so is the empty string
Hello, Bo
Hello, Bo
null, Bo
, Bo
The default applies only when the argument is undefined, whether it was omitted or explicitly passed as undefined. null, 0, "" and false are kept. That's the same rule as destructuring defaults (article 28) and different from the older idiom greeting = greeting || "Hello", which also replaced "" and 0. When you do want null to fall back too, use greeting ?? "Hello" in the body.
Defaults are evaluated on every call
A default expression runs each time it's needed, so [] or {} defaults create a fresh object per call. (Python programmers: this is different from Python, where a default is created once and shared.)
function addItem(item, list = []) {
list.push(item);
return list;
}
console.log(addItem("a"), addItem("b"));
[ 'a' ] [ 'b' ]
Defaults can be any expression, including function calls and earlier parameters:
const rectangle = (width, height = width) => ({ width, height }); // a square by default
console.log(rectangle(4), rectangle(4, 2));
let nextId = 0;
function createTask(title, id = ++nextId) {
return `${id}: ${title}`;
}
console.log(createTask("write"), createTask("test"), createTask("ship", 99), nextId);
{ width: 4, height: 4 } { width: 4, height: 2 }
1: write 2: test 99: ship 2
The ++nextId only ran when no ID was passed. Parameters are initialized left to right, so a default can use parameters before it but not after it: (a = b, b = 1) throws a ReferenceError when a's default is needed (temporal dead zone, article 26).
Required parameters
A default that throws turns a forgotten argument into a clear error:
const required = (name) => {
throw new TypeError(`${name} is required`);
};
function connect(url = required("url"), timeoutMs = 5000) {
return `${url} (${timeoutMs} ms)`;
}
console.log(connect("db.local"));
try {
connect();
} catch (err) {
console.log(err.name, err.message);
}
db.local (5000 ms)
TypeError url is required
Put optional parameters after required ones. A caller can't skip a middle argument except by passing undefined explicitly, which is awkward. For several optional settings, use an options object (below).
Rest parameters: any number of arguments
A parameter written with ... before its name collects all remaining arguments into a real array:
function largest(first = -Infinity, ...others) {
let max = first;
for (const n of others) {
if (n > max) max = n;
}
return max;
}
console.log(largest(3, 9, 4), largest(7), largest());
const describe = (label, ...tags) => `${label}: ${tags.length} tags (${tags.join(", ")})`;
console.log(describe("post", "js", "web"), "|", describe("draft"));
9 7 -Infinity
post: 2 tags (js, web) | draft: 0 tags ()
Rules: the rest parameter must be last, there can be only one, and it can't have a default (it's always an array, empty if there are no extra arguments). Functions that accept any number of arguments are called variadic; console.log, Math.max and Array.of are examples.
The arguments object
Before rest parameters, the only way to reach extra arguments was arguments, an array-like object (article 62) available inside every regular function:
function oldStyleMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) max = arguments[i];
}
return max;
}
console.log(oldStyleMax(4, 8, 2));
8
You'll see arguments in older code and in interview questions, but avoid it in new code:
- It's not a real array: no
map,filterorreducewithout conversion. - Arrow functions don't have their own
arguments; inside one, the name refers to the enclosing function's arguments. - In sloppy-mode functions with simple parameter lists,
argumentsis linked to the parameters: changingarguments[0]changes the first parameter, and vice versa. Strict mode (and any function with defaults, rest or destructuring) breaks that link. - In strict mode,
argumentscan't be used as a variable or parameter name.
// new Function always creates sloppy-mode code, even inside a module
const sloppy = new Function("a", "arguments[0] = 99; return a;");
function strict(a) {
"use strict";
arguments[0] = 99;
return a;
}
console.log(sloppy(1), strict(1));
99 1
A rest parameter (...args) does everything arguments did, as a real array, with none of the quirks.
Spread: an array as separate arguments
Spread syntax in a call does the opposite of a rest parameter: it expands an array (or any iterable) into individual arguments:
const temps = [14, 9, 21];
console.log(Math.min(...temps), Math.max(...temps));
console.log(Math.max(..."391")); // strings are iterable
console.log(Math.max(...[])); // no arguments at all
9 21
9
-Infinity
The same three dots mean "gather into an array" in a parameter list and "spread out" in a call or array literal. Together they make wrapper functions easy: accept any arguments, pass them all on:
function withLogging(fn) {
return function (...args) { // gather
const result = fn(...args); // spread
console.log(`${fn.name}(${args.join(", ")}) -> ${result}`);
return result;
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3);
add(2, 3) -> 5
Very large arrays can exceed the engine's argument limit when spread (article 59).
Destructured parameters
A parameter can be a destructuring pattern (article 28), which unpacks an array or object argument directly:
function addVectors([x1, y1], [x2, y2]) {
return [x1 + x2, y1 + y2];
}
console.log(addVectors([1, 2], [3, 4]));
function label({ id: userId, name }) { // rename id to userId
return `${userId}-${name}`;
}
console.log(label({ id: 7, name: "Cy", extra: true }));
[ 4, 6 ]
7-Cy
In { id: userId }, the property name is on the left of the colon and the new variable on the right, the same position a value would have in an object literal.
Options objects: named arguments
JavaScript has no named arguments like Python's f(timeout=5), but an object parameter with destructuring and defaults works the same way, and it's the standard pattern for functions with several optional settings:
function createUser({ name, role = "viewer", active = true } = {}) {
return `${name}/${role}/${active}`;
}
console.log(createUser({ name: "Ana" }));
console.log(createUser({ active: false, name: "Bo" })); // any order
console.log(createUser()); // works thanks to = {}
Ana/viewer/true
Bo/viewer/false
undefined/viewer/true
Each property gets its own default, and callers name what they pass, in any order. The final = {} matters: without it, calling createUser() tries to destructure undefined and throws a TypeError.
Rest works inside patterns too, collecting the properties you didn't name:
function scale({ x, y, ...others }, factor) {
return { x: x * factor, y: y * factor, ...others };
}
console.log(scale({ x: 1, y: 2, color: "red" }, 3));
{ x: 3, y: 6, color: 'red' }
Deeply nested parameter patterns quickly become hard to read; when that happens, destructure inside the function body instead.
Arguments are passed by sharing
JavaScript passes every argument by value, but for objects the value is a reference (article 21). So a function can modify an object it receives, and the caller sees the change; but reassigning the parameter only changes the local variable:
function update(settings, count) {
settings.theme = "dark"; // changes the caller's object
settings = { theme: "light" }; // only changes the local variable
count++; // primitives: the caller's variable is untouched
return [settings.theme, count];
}
const prefs = { theme: "auto" };
let visits = 1;
console.log(update(prefs, visits), prefs.theme, visits);
[ 'light', 2 ] dark 1
Functions that mutate their arguments surprise callers. Prefer returning new values, or document the mutation clearly.
Checking argument types
JavaScript doesn't check types, and its automatic conversions can turn a wrong argument into a wrong result instead of an error. For functions used across a codebase, validating early and throwing a TypeError with a clear message saves debugging time:
function sumAll(...nums) {
if (!nums.every(Number.isFinite)) {
throw new TypeError("sumAll expects finite numbers");
}
return nums.reduce((total, n) => total + n, 0);
}
console.log(sumAll(1, 2, 3));
try {
sumAll(1, "2");
} catch (err) {
console.log(err.name, err.message);
}
6
TypeError sumAll expects finite numbers
In larger projects, TypeScript (part 17) checks argument types before the code even runs, and JSDoc comments (@param {number} n) document them for editors.
Function length
A function's length property is the number of parameters before the first one with a default or a rest parameter. Libraries sometimes use it, for example to tell callbacks with different arities apart:
console.log(((a, b) => 0).length, ((a, b = 1, c) => 0).length, ((...all) => 0).length);
2 1 0
Common questions
How do I skip an argument in the middle?
Pass undefined: makeBox(10, undefined, "red") uses the second parameter's default. If you need to do that often, the function should take an options object instead.
What's the difference between rest and spread?
Same ... syntax, opposite directions. In a parameter list or destructuring pattern, it gathers values into an array (rest). In a call or array/object literal, it spreads an iterable or object into separate values.
Should I use arguments or rest parameters?
Rest parameters. They're real arrays, they work in arrow functions, and they make the function's signature show that it accepts extra arguments.
How many parameters is too many?
Beyond about three positional parameters, callers start mixing up the order. Switch to an options object: send({ to, subject, body, cc }) is much clearer than send(to, subject, body, null, null, cc).
Summary
- Arguments match parameters by position; missing ones are
undefined, extras are ignored. - Default values (
p = value) apply only forundefined, are evaluated on every call, and can use earlier parameters. - A rest parameter
...args(last, one only) collects extra arguments into a real array; prefer it to the legacyargumentsobject. - Spread
f(...arr)passes array elements as separate arguments. - Destructured parameters unpack arrays and objects; an options object with defaults and
= {}gives you named, optional arguments. - Objects are passed by sharing: mutations are visible to the caller, reassignments aren't.
- Validate arguments where wrong types would silently produce wrong results.
Practice Questions
What does this print?
function f(a, b = a + 1, ...c) {
return [a, b, c];
}
console.log(f(1), f(1, undefined, 3, 4));
Answer
[ 1, 2, [] ] [ 1, 2, [ 3, 4 ] ]. Both calls leave b undefined, so its default a + 1 is used; the rest parameter collects whatever comes after b.
Why does this code throw when called as setup(), and how do you fix it?
function setup({ debug = false }) {
...
}
Answer
Without an argument, the parameter is undefined, which can't be destructured: TypeError. Add a default for the whole object: function setup({ debug = false } = {}).
Write average(...nums) that returns 0 for no arguments.
Answer
const average = (...nums) => (nums.length === 0 ? 0 : nums.reduce((s, n) => s + n, 0) / nums.length);
What does this print?
function g(x) {
x.push(4);
x = [9];
return x;
}
const arr = [1];
console.log(g(arr), arr);
Answer
[ 9 ] [ 1, 4 ]. push changes the caller's array; reassigning x only rebinds the local parameter.
Previous: Calling JavaScript Functions: Methods, this, Constructors, Recursion and the Call Stack

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.