Parameters and arguments
Overview
Parameters are the names in a function’s definition; arguments are the values you pass in. JavaScript is relaxed about them: pass too few and the missing ones are undefined; pass too many and the extras are ignored. No error either way.
function greet(name, greeting) {
return `${greeting}, ${name}!`;
}
greet('Asha'); // 'undefined, Asha!'
greet('Asha', 'Hi', 'extra'); // 'Hi, Asha!' — 'extra' ignoredThat flexibility is useful, but it means you have to handle missing values. This topic shows the tools for doing that cleanly.
Default values
function greet(name, greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
greet('Asha'); // 'Hello, Asha!'
greet('Asha', 'Welcome'); // 'Welcome, Asha!'Defaults are used only when the argument is undefined — passing null or 0 keeps that value:
function setVolume(level = 50) {
return level;
}
setVolume(); // 50
setVolume(undefined); // 50
setVolume(0); // 0
setVolume(null); // nullA default can be any expression, and can use earlier parameters:
function createId(prefix = 'id', time = Date.now()) {
return `${prefix}-${time}`;
}
function rectangle(width, height = width) {
return width * height; // a square if height is left out
}Defaults are evaluated fresh on each call, so time above gets a new value every time.
Required parameters
JavaScript has no built-in “required” marker. A neat trick is a default that throws:
function required(name) {
throw new Error(`Missing argument: ${name}`);
}
function sendEmail(to = required('to'), subject = '') {
// …
}
sendEmail(); // Error: Missing argument: toRest parameters
Put ... before the last parameter to collect any number of arguments into a real array:
function logAll(label, ...items) {
for (const item of items) console.log(label, item);
}
logAll('Topic:', 'Loops', 'Functions', 'Objects');
// Topic: Loops
// Topic: Functions
// Topic: ObjectsBecause it’s a real array, you can use length, map, reduce and the rest:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(); // 0
sum(1, 2, 3); // 6A function can have only one rest parameter, and it must be last — function f(...a, b) is a syntax error.
The old arguments object
Regular functions (not arrow functions) also have a built-in arguments object holding every argument passed. It looks like an array but isn’t one, so it lacks methods like map. Rest parameters replace it in modern code:
function oldStyle() {
return arguments.length;
}Spreading arguments
The same ... syntax does the opposite in a call — it spreads an array out into separate arguments:
const scores = [7, 12, 9];
Math.max(...scores); // 12 — same as Math.max(7, 12, 9)
Math.max(scores); // NaN — an array isn't a numberYou can mix spread with normal arguments, and spread several arrays:
const morning = [3, 8];
const evening = [5, 11];
Math.max(0, ...morning, ...evening); // 11Rest gathers, spread scatters.
...in a function’s definition collects arguments into an array;...in a call (or an array literal) expands an array into items.
Arguments are copied
When you pass a primitive (a number, string, boolean…), the function gets its own copy. Changing the parameter doesn’t affect the caller:
function addOne(n) {
n = n + 1;
return n;
}
let x = 5;
addOne(x); // 6
console.log(x); // 5 — unchangedObjects and arrays are different: the function receives a reference to the same object, so changing its contents is visible outside:
function addItem(cart) {
cart.push('apple'); // changes the caller's array!
}
const myCart = [];
addItem(myCart);
console.log(myCart); // ['apple']Functions that change their inputs like this can be surprising. Often it’s cleaner to return a new array instead: return [...cart, 'apple'];.
Named options
When a function takes several optional settings, accept one object and destructure it. Callers then don’t have to remember the order:
function createCourse({ title, level = 'Beginner', published = false }) {
return { title, level, published };
}
createCourse({ title: 'SQL', published: true });Compare the call with positional arguments: createCourse('SQL', undefined, true). It’s impossible to tell what true means without looking up the function. The options object documents itself.
Add = {} so the function can be called with no argument at all:
function connect({ host = 'localhost', port = 8080 } = {}) {
return `${host}:${port}`;
}
connect(); // 'localhost:8080'
connect({ port: 3000 }); // 'localhost:3000'A common pattern is to keep one or two essential arguments positional and put everything optional in an options object: fetch(url, { method: 'POST' }) works exactly this way.
Average of any numbers
Write average(...nums) that returns the average of however many numbers are passed, or 0 if none are. Then call it with the numbers in the scores array.
function average(...nums) {
// your code here
}
const scores = [8, 6, 10];
// call average with scores herefunction average(...nums) {
if (nums.length === 0) return 0;
return nums.reduce((sum, n) => sum + n, 0) / nums.length;
}
const scores = [8, 6, 10];
average(...scores); // 8Summary
- Arguments fill parameters by position; missing ones are
undefined, extras are ignored. - Default parameters kick in only when an argument is
undefined. - A rest parameter
...argsgathers extra arguments into an array; it must come last. - Spread
...arrayexpands an array into separate arguments. - For several optional settings, accept one options object and destructure it.