All topics
Functionsbeginner

Default Parameters

How to give function parameters fallback values that are used automatically when no argument or undefined is passed.

Default parameters, added in ES6, let you specify a fallback value directly in a function's parameter list, which the engine uses automatically whenever the corresponding argument is omitted or explicitly passed as undefined. This replaced a pattern of manual || checks inside the function body, and it's a small but frequently tested topic because its evaluation timing and interaction with other parameters has real subtlety.

Default parameters are like a restaurant order form that already has 'medium spice' pre-checked — if you don't specify a spice level, you get medium automatically, but if you explicitly circle 'no spice' (an intentional falsy-ish choice), the kitchen respects that instead of silently defaulting you back to medium.

Key Concepts

1
A default parameter is written as function greet(name = 'Guest') {}; if greet() is called with no arguments, name becomes 'Guest'. Critically, the default only kicks in for undefined, not for other falsy values — calling greet(null) or greet(0) does *not* trigger the default, since those are legitimate values being explicitly passed, not an omission. This is more precise than the old name = name || 'Guest' pattern, which incorrectly overrode any falsy argument, including 0, '', or false, with the default.
function greet(name = 'Guest') {}greet()name'Guest'undefined
2
Default values are evaluated lazily, at call time, not once when the function is defined — so function log(time = Date.now()) {} gets a fresh timestamp on every call where time is omitted, not the timestamp from when log was first defined. Default parameters can also reference earlier parameters in the same list (function f(a, b = a * 2)), since parameters are evaluated left to right, but they cannot reference parameters declared after them.
function log(time = Date.now()) {}timelogfunction f(a, b = a * 2)
3
Default parameters combine naturally with destructuring to give clean fallback behavior for options-object-style function signatures, a very common pattern in real codebases: function createUser({ name, role = 'member' } = {}) {} handles both missing individual properties and a completely missing argument object in one concise declaration.
function createUser({ name, role = 'member' } = {}) {}