Parameters and arguments

Topic 3 of 6 in Functions7 min readBeginnerFree course

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.

JavaScript
function greet(name, greeting) {
  return `${greeting}, ${name}!`;
}
greet('Asha');                    // 'undefined, Asha!'
greet('Asha', 'Hi', 'extra');     // 'Hi, Asha!' — 'extra' ignored

That flexibility is useful, but it means you have to handle missing values. This topic shows the tools for doing that cleanly.

For function order(item, qty = 1, …extras) called as order(‘Tea’, undefined, ‘milk’, ‘sugar’): ‘Tea’ fills item by position; undefined means qty’s default of 1 is used; the remaining ‘milk’ and ‘sugar’ are gathered into the array extras.

Default values

JavaScript
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:

JavaScript
function setVolume(level = 50) {
  return level;
}
setVolume();          // 50
setVolume(undefined); // 50
setVolume(0);         // 0
setVolume(null);      // null

A default can be any expression, and can use earlier parameters:

JavaScript
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:

JavaScript
function required(name) {
  throw new Error(`Missing argument: ${name}`);
}

function sendEmail(to = required('to'), subject = '') {
  // …
}

sendEmail(); // Error: Missing argument: to

Rest parameters

Put ... before the last parameter to collect any number of arguments into a real array:

JavaScript
function logAll(label, ...items) {
  for (const item of items) console.log(label, item);
}
logAll('Topic:', 'Loops', 'Functions', 'Objects');
// Topic: Loops
// Topic: Functions
// Topic: Objects

Because it’s a real array, you can use length, map, reduce and the rest:

JavaScript
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
sum();           // 0
sum(1, 2, 3);    // 6

A 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:

JavaScript
function oldStyle() {
  return arguments.length;
}

Spreading arguments

The same ... syntax does the opposite in a call — it spreads an array out into separate arguments:

JavaScript
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 number

You can mix spread with normal arguments, and spread several arrays:

JavaScript
const morning = [3, 8];
const evening = [5, 11];
Math.max(0, ...morning, ...evening); // 11

Rest 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:

JavaScript
function addOne(n) {
  n = n + 1;
  return n;
}
let x = 5;
addOne(x);   // 6
console.log(x); // 5 — unchanged

Objects and arrays are different: the function receives a reference to the same object, so changing its contents is visible outside:

JavaScript
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:

JavaScript
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:

JavaScript
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.

Exercise

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.

JavaScript
function average(...nums) {
  // your code here
}

const scores = [8, 6, 10];
// call average with scores here

Summary

  • 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 ...args gathers extra arguments into an array; it must come last.
  • Spread ...array expands an array into separate arguments.
  • For several optional settings, accept one options object and destructure it.