Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Function

Default parameters

Reference for JavaScript default parameters: set fallback values, how undefined triggers them, evaluation order, expressions and destructured defaults.

A default parameter gives a parameter a fallback value that is used when the caller passes undefined or passes nothing at all. You write it with = after the parameter name. It replaces the old habit of writing name = name || "guest" inside the function body.

The default can be any expression. It is evaluated each time the function is called, not once when the function is defined.

JavaScript
function greet(name = "friend") {
  return `Hello, ${name}!`;
}

Try it

JS Defaults and undefined

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Expressions, earlier parameters and destructuring

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
function name(param1 = defaultValue1, param2 = defaultValue2) {
  // ...
}

const fn = (a, b = 10) => a + b;
Name Description
defaultValue Any expression. It runs only when the argument is undefined or missing.

Usage notes

  • Only undefined triggers the default. null, 0, "", false and NaN are real values and are kept. That is the main difference from value || fallback.
  • Evaluated at call time. A new object or array in the default is created for every call, and side effects such as ++calls run each time (and only when needed).
  • Earlier parameters are visible to later defaults (height = width), but not the other way round. Using a parameter before it is initialized throws a ReferenceError, as the last example shows.
  • Destructured parameters can have defaults for each property and a default for the whole object (= {}), which makes the argument optional.
  • length shrinks. A function's length property counts parameters before the first one with a default, so greet.length is 0.
  • Separate scope. When a function has default parameters, the parameters live in their own scope; variables declared in the body do not leak into the default expressions.
  • Default values and arguments: the arguments object does not receive defaults; it contains only what the caller really passed.
  • Style: put parameters with defaults last so callers can omit them.
  • Required arguments: use a default that throws to make a parameter mandatory, for example x = required("x"), where required is a function you define.

Browser support

Default parameters are supported in every current browser and JavaScript runtime.