Beginner · Functions and closures · topic 13 of 61 · 20 min
Parameters: defaults, rest and options objects
Explanation
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.
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.
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 quotaRest 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.
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, dalSpread when calling
The same three dots used in a CALL do the opposite: they spread an array out into separate arguments.
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.
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'));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
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.
function paymentRequest(payee, amount, { note = '', expiryMinutes = 15, currency = 'INR' } = {}) {
return { payee, amount, note, expiryMinutes, currency };
}
console.log(paymentRequest('shop@upi', 250, { note: 'Groceries' }));Practice (0/3 done)
Write greet(name, greeting = "Namaste") that returns "<greeting>, <name>!". greet("Asha") returns "Namaste, Asha!".
Write average(...nums) that returns the average of any number of numbers, or 0 when none are given.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Scope and closuresFunctions and closures · same module
- Destructuring, spread and restArrays and objects
- *args and **kwargsPython Programming · Functions
- Parameters, arguments and defaultsPython Programming · Functions
- More array powerFrontend Web Development · JavaScript in depth
- Parameters in depth: optional, named, ref, out, params, overloadingC# and .NET · Decisions, loops and methods
Questions people ask about this
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
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.
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
- 2 more topics in “Functions and closures” before its exam: Scope and closures, Higher-order functions and recursion.
- Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and objects. 61 topics left in the course before the final exam.