Skip to content

Beginner · Functions and closures · topic 13 of 61 · 20 min

Parameters: defaults, rest and options objects

Explanation

JavaScript does not check how many arguments you pass: missing ones become undefined and extra ones are ignored. Default parameters fill in missing values, rest parameters (...args) collect any number of arguments into an array, and spread (...) does the opposite at the call. An options object with destructuring makes functions with many settings readable.

Missing and extra arguments

Many languages refuse to run if you pass the wrong number of arguments. JavaScript does not. A missing argument becomes undefined, and an extra argument is simply ignored. This is flexible, but it can hide mistakes.

javascript
function fullName(first, last) {
  return first + ' ' + last;
}
console.log(fullName('Asha'));               // 'Asha undefined'
console.log(fullName('Asha', 'Rao', 'Extra')); // 'Asha Rao'

Default parameters

A default value is used when the argument is missing OR is undefined. It is written with = in the parameter list. Defaults are calculated each time the function is called, and they can use earlier parameters.

javascript
function bookSeat(name, berth = 'any', quota = 'GN') {
  return `${name}: ${berth} berth, ${quota} quota`;
}
console.log(bookSeat('Ravi'));                 // Ravi: any berth, GN quota
console.log(bookSeat('Ravi', 'lower'));        // Ravi: lower berth, GN quota
console.log(bookSeat('Ravi', undefined, 'TQ')); // Ravi: any berth, TQ quota
console.log(bookSeat('Ravi', null));           // Ravi: null berth, GN quota
Passing undefined uses the default; passing null does not.
Careful: Defaults apply only to undefined, not to null, 0 or ''. If an API sends null for "not chosen", the default will not kick in. Handle null with ?? inside the function: berth = berth ?? 'any'.

Rest parameters: any number of arguments

Three dots before the LAST parameter collect all remaining arguments into a real array. This is called a rest parameter. Old code used the special arguments object instead, which is array-like but has no array methods; prefer rest.

javascript
function total(...amounts) {
  let sum = 0;
  for (const a of amounts) sum += a;
  return sum;
}
console.log(total(100, 250, 75)); // 425
console.log(total());             // 0

function tagged(label, ...items) {
  return `${label}: ${items.join(', ')}`;
}
console.log(tagged('Veg', 'paneer', 'dal')); // Veg: paneer, dal

Spread when calling

The same three dots used in a CALL do the opposite: they spread an array out into separate arguments.

javascript
const marks = [78, 92, 64];
console.log(Math.max(...marks)); // 92 (same as Math.max(78, 92, 64))

Options objects

A function with many parameters is hard to call correctly: sendSms('98…', 'Hi', true, false, 3) — what does true mean? Instead, pass one object with named settings and destructure it in the parameter list, with defaults. The call now explains itself and the order no longer matters.

javascript
function sendSms(to, text, { priority = 'normal', retries = 2, unicode = false } = {}) {
  return `to ${to}: "${text}" [${priority}, retries ${retries}, unicode ${unicode}]`;
}
console.log(sendSms('9876543210', 'Your OTP is 4821', { priority: 'high' }));
console.log(sendSms('9876543210', 'Hello'));
The = {} at the end lets callers leave out the options object completely.
Think of it like this: An options object is like a restaurant order slip with labelled boxes: "spice: medium, onion: no, extra cheese: yes". The cook does not care in which order you ticked the boxes, and anything you left blank uses the house default.
Tip: Rule of thumb: up to two or three required parameters in a row, then one options object for everything optional.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Parameters: defaults, rest and options objects · 1/6

Parameters

In this lesson you will pass arguments in flexible ways: defaults, rest, spread and options objects.

Prefer a video by a teacher? Find free videos on “javascript default parameters rest spread options object” on YouTube ↗

In real life: A UPI payment request builder

Payment code builds a request with many optional fields: a note, an expiry, a reference number. An options object with defaults keeps every call short and readable, and new options can be added later without breaking old calls.

javascript
function paymentRequest(payee, amount, { note = '', expiryMinutes = 15, currency = 'INR' } = {}) {
  return { payee, amount, note, expiryMinutes, currency };
}
console.log(paymentRequest('shop@upi', 250, { note: 'Groceries' }));
Prints { payee: 'shop@upi', amount: 250, note: 'Groceries', expiryMinutes: 15, currency: 'INR' }.

Practice (0/3 done)

Task 1 · Code · Javascript

Write greet(name, greeting = "Namaste") that returns "<greeting>, <name>!". greet("Asha") returns "Namaste, Asha!".

Task 2 · Code · Javascript

Write average(...nums) that returns the average of any number of numbers, or 0 when none are given.

Task 3 · Code · Javascript

Write formatPrice(amount, options) where options may contain symbol (default "₹") and decimals (default 2), and may be left out completely. formatPrice(50) returns "₹50.00"; formatPrice(9.5, { symbol: "$", decimals: 1 }) returns "$9.5".

Quick quiz

Question 1

1.function f(a, b = 10) { return a + b; } What is f(5, null)?

Question 2

2.In function f(...args), what is args?

Question 3

3.What is Math.min(...[4, 2, 8])?

Question 4

4.Where must a rest parameter go?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

function f(a, b = 10) { return a + b; } What is f(5, null)?

Answer: 5

null does not trigger the default; 5 + null is 5 because null becomes 0.

In function f(...args), what is args?

Answer: A real array

A rest parameter is a real array of the remaining arguments.

What is Math.min(...[4, 2, 8])?

Answer: 2

Spread turns the array into separate arguments: Math.min(4, 2, 8).

Where must a rest parameter go?

Answer: Last

Rest collects everything that is left, so it must be the last parameter.

In function f(...args), the three dots are called…Related

Answer: rest

In a parameter list they collect arguments: rest.

From Destructuring, spread and rest

Which def line has the parameters in a valid order?Related

Answer: def f(*args, a, **kw):

The order is positional, defaults, *args, keyword-only, **kwargs. Here a after *args is keyword-only, which is allowed.

From *args and **kwargs

def power(n, p=2): return n ** p. What is power(3)?Related

Answer: 9

p is left out, so the default 2 is used: 3 ** 2 = 9.

From Parameters, arguments and defaults

const [a, ...rest] = [1, 2, 3]; What is rest?Related

Answer: [2, 3]

a takes the first item, and ...rest collects everything that is left into a new array.

From More array power

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Functions and closures” before its exam: Scope and closures, Higher-order functions and recursion.
  2. Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and objects. 61 topics left in the course before the final exam.

← Previous: Arrow functions