What are default parameters?

Default parameters let you give a function parameter a fallback value that is used when the argument is missing or explicitly undefined.

How they behave

  • Defaults apply only for undefined. Passing null, 0, false or "" keeps that value.
  • Defaults are evaluated at call time, every time. function f(list = []) gets a new array on each call, which avoids the shared-default bug some other languages have.
  • A default can use earlier parameters: function range(start, end = start + 10).
  • A default can call a function: function save(id = crypto.randomUUID()).
  • Parameters with defaults (and everything after them) are not counted in fn.length.

Combine with destructuring

function connect({ host = "localhost", port = 5432 } = {}) gives each option a default and makes the whole options object optional.

Required parameters

A neat trick: function f(id = required("id")) where required throws. The error only happens when the argument is missing.

Before ES2015

Code used x = x || defaultValue, which wrongly replaced 0, "" and false. Default parameters (or ??) fix that.

Code example

js
1function greet(name = "friend", greeting = `Hello`) {
2 return `${greeting}, ${name}!`;
3}
4console.log(greet()); // Hello, friend!
5console.log(greet("Ada")); // Hello, Ada!
6console.log(greet(undefined, "Hi")); // Hi, friend!
7console.log(greet(null)); // Hello, null! <- null is a real value
8
9// Evaluated on every call: no shared array between calls
10function addItem(item, list = []) {
11 list.push(item);
12 return list;
13}
14console.log(addItem("a"), addItem("b")); // ["a"] ["b"]
15
16// Defaults can use earlier parameters
17const range = (start, end = start + 3) => Array.from({ length: end - start }, (_, i) => start + i);
18console.log(range(5)); // [5, 6, 7]
19
20// Required parameter pattern
21const required = (name) => {
22 throw new Error(`${name} is required`);
23};
24function fetchUser(id = required("id")) {
25 return { id };
26}
27try {
28 fetchUser();
29} catch (e) {
30 console.log(e.message); // id is required
31}
32
33console.log(greet.length); // 0 (params with defaults are not counted)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app