JavaScript Function Parameters: Default, Rest, Spread and Options Objects
Real functions need flexible input: an optional timeout, any number of tags, or a configuration with ten settings where you only change two. Modern JavaScript gives you default parameters, rest parameters, spread arguments and destructured options objects for exactly these cases, and Playwright’s own API uses all of them. In this lesson you will learn each one, how they interact with undefined and null, and how to validate parameters so bad input fails with a clear message.
📖 What You’ll Learn: default parameter values and when they apply, defaults that use earlier parameters, rest parameters, the legacy arguments object, spreading arrays into arguments, the options-object pattern with destructuring and defaults, required parameters and validation, and function length.
🎛️ Default Parameters
Definition: a default parameter gives a parameter a value to use when the caller does not pass one (or passes undefined). Write it with = in the parameter list.
📄 defaults.js
function greet(name = "guest", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet());
console.log(greet("Asha"));
console.log(greet("Asha", "Welcome back"));
console.log(greet(undefined, "Hi")); // undefined triggers the default
console.log(greet(null)); // null does NOT trigger it
⌨️ Terminal
node defaults.js
🖥️ Output
Hello, guest!
Hello, Asha!
Welcome back, Asha!
Hi, guest!
Hello, null!
⚠️ Watch out: Defaults apply only to undefined. If an API or form gives you null or an empty string, the default is not used. Normalise such values first, for example with value ?? fallback.
Before ES2015, people wrote name = name || "guest" inside the function. That also replaced 0, "" and false, which is why default parameters are safer.
🔗 Defaults That Use Other Parameters or Expressions
A default can be any expression. It is evaluated each time the function is called without that argument, and it can use parameters listed before it:
📄 default-expr.js
function createRun(suite, startedAt = new Date().toISOString().slice(0, 10), id = `${suite}-${startedAt}`) {
return { suite, startedAt, id };
}
console.log(createRun("smoke", "2026-11-23"));
console.log(createRun("smoke", "2026-11-23", "custom-id"));
function addTag(tag, list = []) { // a fresh array on every call
list.push(tag);
return list;
}
console.log(addTag("ui"), addTag("api"));
⌨️ Terminal
node default-expr.js
🖥️ Output
{ suite: 'smoke', startedAt: '2026-11-23', id: 'smoke-2026-11-23' }
{ suite: 'smoke', startedAt: '2026-11-23', id: 'custom-id' }
[ 'ui' ] [ 'api' ]
💡 Tip: Because the default [] is created again on every call, the two addTag calls do not share an array. (Python developers will know this is different in Python.)
🧺 Rest Parameters (…args)
Definition: a rest parameter, written ...name, collects all remaining arguments into a real array. It must be the last parameter.
📄 rest.js
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(), sum(5), sum(1, 2, 3, 4));
function logStep(level, ...messages) {
console.log(`[${level.toUpperCase()}]`, messages.join(" "));
}
logStep("info", "Opening", "login", "page");
logStep("warn", "Retrying", "attempt", 2);
⌨️ Terminal
node rest.js
🖥️ Output
0 5 10
[INFO] Opening login page
[WARN] Retrying attempt 2
Putting the rest parameter anywhere but last is a syntax error:
📄 rest-error.js
function bad(...items, last) {
return items;
}
⌨️ Terminal
node rest-error.js
🖥️ Output
/home/you/js-course/rest-error.js:1
function bad(...items, last) {
^
SyntaxError: Rest parameter must be last formal parameter
Node.js v26.13.0
📜 The arguments Object (Legacy)
Regular functions also have a built-in arguments object containing every argument. It is array-like (it has length and indexes) but it is not an array, and arrow functions do not have it.
📄 arguments.js
function legacySum() {
console.log(arguments.length, Array.isArray(arguments));
let total = 0;
for (let i = 0; i < arguments.length; i++) total += arguments[i];
return total;
}
console.log(legacySum(2, 4, 6));
const modernSum = (...nums) => nums.reduce((a, b) => a + b, 0);
console.log(modernSum(2, 4, 6));
⌨️ Terminal
node arguments.js
🖥️ Output
3 false
12
12
You will meet arguments in older code. In new code, always use rest parameters.
🌊 Spread Arguments
Spread is the opposite of rest: ...array in a function call expands an array into separate arguments.
📄 spread.js
const responseTimes = [320, 1290, 450, 980];
console.log(Math.max(responseTimes)); // an array is one argument: NaN
console.log(Math.max(...responseTimes)); // spread into four arguments
function fullName(first, last) {
return `${first} ${last}`;
}
const parts = ["Asha", "Rao"];
console.log(fullName(...parts));
console.log(Math.min(0, ...responseTimes, 2000)); // mix with other arguments
⌨️ Terminal
node spread.js
🖥️ Output
NaN
1290
Asha Rao
0
| Syntax | Where | What it does |
|---|---|---|
function f(...args) | Parameter list | Rest: collects arguments into an array |
f(...arr) | Function call | Spread: expands an array into arguments |
[...a, ...b], { ...obj } | Array/object literals | Spread: copies items or properties |
🧰 The Options Object Pattern
Long parameter lists are hard to read: in launch("chromium", true, 3, 30000, false), what does 3 mean? The options object pattern passes one object with named properties instead. Destructuring with defaults unpacks it in the parameter list:
📄 options.js
function launch({ browser = "chromium", headless = true, retries = 0, timeout = 30000 } = {}) {
return `${browser} headless=${headless} retries=${retries} timeout=${timeout}`;
}
console.log(launch());
console.log(launch({ retries: 2 }));
console.log(launch({ browser: "firefox", headless: false }));
⌨️ Terminal
node options.js
🖥️ Output
chromium headless=true retries=0 timeout=30000
chromium headless=true retries=2 timeout=30000
firefox headless=false retries=0 timeout=30000
- The call sites are self-documenting:
{ retries: 2 }says what 2 means. - Callers pass only the options they want to change, in any order.
- The
= {}at the end lets you calllaunch()with no argument at all. Without it, destructuringundefinedthrows aTypeError.
📄 options-error.js
function launchNoDefault({ browser = "chromium" }) {
return browser;
}
console.log(launchNoDefault({}));
console.log(launchNoDefault());
⌨️ Terminal
node options-error.js
🖥️ Output
chromium
/home/you/js-course/options-error.js:1
function launchNoDefault({ browser = "chromium" }) {
^
TypeError: Cannot read properties of undefined (reading 'browser')
at launchNoDefault (/home/you/js-course/options-error.js:1:28)
at Object.<anonymous> (/home/you/js-course/options-error.js:5:13)
Node.js v26.13.0
Playwright uses this pattern everywhere, for example page.click(selector, { timeout: 5000 }) and page.screenshot({ path: "home.png", fullPage: true }).
✅ Required Parameters and Validation
JavaScript does not enforce required parameters. Validate important inputs at the start of the function and throw a clear error:
📄 validate.js
function required(name) {
throw new Error(`Missing required parameter: ${name}`);
}
function createUser(email = required("email"), role = "tester") {
if (typeof email !== "string" || !email.includes("@")) {
throw new TypeError(`Invalid email: ${JSON.stringify(email)}`);
}
return { email, role };
}
console.log(createUser("qa@sqatools.in"));
for (const bad of [undefined, 42, "no-at-sign"]) {
try {
createUser(bad);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
}
⌨️ Terminal
node validate.js
🖥️ Output
{ email: 'qa@sqatools.in', role: 'tester' }
Error: Missing required parameter: email
TypeError: Invalid email: 42
TypeError: Invalid email: "no-at-sign"
email = required("email") uses a default expression that throws: it runs only when the argument is missing.
💡 Tip: TypeScript or JSDoc types catch many parameter mistakes before the code runs. In plain JavaScript, validating at the boundary (public helpers, API clients) gives fast, readable failures.
📏 Function length
A function’s length property is the number of parameters declared before the first default or rest parameter. Some libraries use it to decide how to call a function.
📄 length.js
function a(x, y) {}
function b(x, y = 1) {}
function c(...rest) {}
const d = ({ timeout } = {}) => {};
console.log(a.length, b.length, c.length, d.length);
⌨️ Terminal
node length.js
🖥️ Output
2 1 0 0
🧪 Tester Scenario: A Flexible API Request Helper
📄 request.js
function buildRequest(path, { method = "GET", headers = {}, body, retries = 1, ...extra } = {}) {
if (!path.startsWith("/")) throw new Error(`Path must start with "/": ${path}`);
return {
url: `https://api.example.com${path}`,
method,
headers: { "content-type": "application/json", ...headers },
body: body === undefined ? undefined : JSON.stringify(body),
retries,
extra,
};
}
console.log(buildRequest("/users"));
console.log(buildRequest("/users", {
method: "POST",
body: { name: "Asha" },
headers: { authorization: "Bearer test-token" },
timeout: 5000,
}));
⌨️ Terminal
node request.js
🖥️ Output
{
url: 'https://api.example.com/users',
method: 'GET',
headers: { 'content-type': 'application/json' },
body: undefined,
retries: 1,
extra: {}
}
{
url: 'https://api.example.com/users',
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: 'Bearer test-token'
},
body: '{"name":"Asha"}',
retries: 1,
extra: { timeout: 5000 }
}
- The options object is destructured with defaults, and
...extracollects any options the helper does not know about (heretimeout), so they are not silently lost. { "content-type": "application/json", ...headers }merges caller headers over the default header.- The path check is a guard clause that turns a common mistake into a clear error.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write power(base, exponent = 2) and print power(5) and power(2, 10).
Show answer
📄 practice1.js
function power(base, exponent = 2) {
return base ** exponent;
}
console.log(power(5), power(2, 10));🖥️ Output
25 1024Q2. Write average(...numbers) that returns the average of any number of arguments, or 0 when called with none.
Show answer
📄 practice2.js
function average(...numbers) {
if (numbers.length === 0) return 0;
return numbers.reduce((a, b) => a + b, 0) / numbers.length;
}
console.log(average(), average(10), average(2, 4, 9));🖥️ Output
0 10 5Q3. Print the largest and smallest value of [17, 3, 99, 42] with Math.max and Math.min using spread.
Show answer
📄 practice3.js
const values = [17, 3, 99, 42];
console.log(Math.max(...values), Math.min(...values));🖥️ Output
99 3Q4. Predict the output, then run it.
function f(a = 1, b = a + 1) {
return [a, b];
}
console.log(f(), f(5), f(5, 0), f(undefined, 9), f(null));Show answer
📄 practice4.js
function f(a = 1, b = a + 1) {
return [a, b];
}
console.log(f(), f(5), f(5, 0), f(undefined, 9), f(null));🖥️ Output
[ 1, 2 ] [ 5, 6 ] [ 5, 0 ] [ 1, 9 ] [ null, 1 ]Defaults apply only to undefined. With f(null), a is null and b = null + 1 = 1.
Q5. Rewrite screenshot(name, fullPage, type, quality) as a function that takes an options object with defaults fullPage: false, type: "png", quality: 80, and returns a summary string.
Show answer
📄 practice5.js
function screenshot(name, { fullPage = false, type = "png", quality = 80 } = {}) {
return `${name}.${type} fullPage=${fullPage} quality=${quality}`;
}
console.log(screenshot("home"));
console.log(screenshot("checkout", { fullPage: true, type: "jpeg" }));🖥️ Output
home.png fullPage=false quality=80
checkout.jpeg fullPage=true quality=80Q6. Write joinPath(...segments) that joins any number of URL segments with /, removing extra slashes at the ends of each segment.
Show answer
📄 practice6.js
function joinPath(...segments) {
return segments
.map((s) => String(s).replace(/^\/+|\/+$/g, ""))
.filter((s) => s.length > 0)
.join("/");
}
console.log(joinPath("https://api.example.com/", "/v1/", "users", 42));🖥️ Output
https://api.example.com/v1/users/42🧠 MCQ Quiz: Default, Rest and Spread Parameters
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- When is a default parameter value used?Answer: When the argument is missing or undefined. null, 0, “” and false do not trigger defaults.
- What does
((x = 5) => x)(null)return?Answer: null. null is a real value, so the default is not applied. - What does a rest parameter collect its values into?Answer: A real array. Rest parameters are true arrays with all array methods.
- Where must a rest parameter appear?Answer: Last in the parameter list. Anything after it is a SyntaxError.
- What does
Math.max(...[3, 9, 4])return?Answer: 9. Spread passes the items as separate arguments. - Which functions have an
argumentsobject?Answer: Regular (non-arrow) functions. Arrow functions use the enclosing function’s arguments, if any. - Why add
= {}after a destructured options parameter?Answer: So the function can be called with no argument. Destructuring undefined would throw a TypeError. - What is
(function (a, b = 2, c) {}).length?Answer: 1. length counts parameters before the first default. - What is the main benefit of the options object pattern?Answer: Named, optional, order-independent arguments. Call sites become self-documenting.
- Is a default parameter expression evaluated once or on every call?Answer: On every call that needs it. A default [] gives a new array on each call.
💼 Interview Questions and Answers
Q1. What is the difference between rest and spread?
They use the same ... syntax for opposite jobs. Rest appears in a parameter list or destructuring pattern and gathers several values into one array (or object). Spread appears in a call or an array/object literal and expands one array (or object) into separate items. function f(...args) {} is rest; f(...list) is spread.
Q2. Why are default parameters better than x = x || defaultValue?
|| replaces every falsy value, so legitimate inputs such as 0, "" and false become the default (a timeout of 0 or headless: false would be lost). Default parameters apply only to undefined, they are visible in the function signature, and they can be expressions using earlier parameters.
Q3. How do you implement a required parameter in JavaScript?
Either validate inside the function (if (email === undefined) throw new Error(...)), or use a default expression that throws, function f(email = required("email")), which only runs when the argument is missing. In TypeScript, parameters are required unless marked optional, so the compiler enforces it.
Q4. Explain this code and its output.
📄 connect.js
function connect({ host = "localhost", port = 5432 } = {}, ...flags) {
return `${host}:${port} ${flags.join(",") || "no flags"}`;
}
console.log(connect());
console.log(connect({ port: 6543 }, "ssl", "readonly"));
⌨️ Terminal
node connect.js
🖥️ Output
localhost:5432 no flags
localhost:6543 ssl,readonly
The first parameter destructures an options object with defaults and falls back to {} when missing. ...flags collects any extra arguments into an array. With no flags, flags.join(",") is an empty string, so || "no flags" supplies the text.
❓ Frequently Asked Questions
🤔 Can a default parameter refer to another parameter?
Yes, to parameters declared before it: function f(a, b = a * 2). Referring to a later parameter throws a ReferenceError.
🤔 Is arguments deprecated?
Not removed, but discouraged. Rest parameters give a real array, work in arrow functions and make the signature clearer.
🤔 How do I make a parameter optional in JavaScript?
Every parameter is optional; a missing one is undefined. Give it a default value or handle undefined explicitly.
🤔 How many parameters can a JavaScript function have?
There is no practical limit, but more than three positional parameters is hard to read. Switch to an options object.
🏁 Summary
- Default parameters (
x = 5) apply only when the argument isundefined, and are evaluated on every call. - Rest parameters (
...args) collect remaining arguments into an array and must come last. - Spread (
f(...arr)) expands an array into separate arguments. - The options object pattern with destructuring and
= {}gives named, optional, order-free arguments. - Validate required parameters early and throw clear errors.
Next, continue with Lesson 20: Scope and Hoisting.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in