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.
function greet(name = "friend") { return `Hello, ${name}!`; }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
undefinedtriggers the default.null,0,"",falseandNaNare real values and are kept. That is the main difference fromvalue || fallback. - Evaluated at call time. A new object or array in the default is created for every call, and side effects such as
++callsrun 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 aReferenceError, 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. lengthshrinks. A function'slengthproperty counts parameters before the first one with a default, sogreet.lengthis0.- 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: theargumentsobject 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"), whererequiredis a function you define.
Browser support
Default parameters are supported in every current browser and JavaScript runtime.