How do you define default parameter values in JavaScript functions? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you define default parameter values in JavaScript functions?

message-square
0

To define default parameter values in JavaScript functions, assign a fallback expression directly in the parameter list using = (such as function greet(name = "Guest") {}), which takes effect whenever the corresponding argument is omitted or explicitly passed as undefined. Default parameters are evaluated at call time (left-to-right), so they can reference earlier parameters or invoke helper functions dynamically, while passing null does not trigger a default value because null is not undefined.


1. Basic Default Parameter Syntax (param = defaultValue)

Place = <expression> right after any parameter in a function declaration, function expression, or arrow function to supply a fallback when the argument is undefined:

// Define default parameter values in function declarations and arrow functions
function formatGreeting(name = "Guest", punctuation = "!") {
  return `Hello, ${name}${punctuation}`;
}

const createPagination = (page = 1, pageSize = 20) => ({
  page,
  pageSize
});

// Example usage:
console.log(formatGreeting());                  // "Hello, Guest!"
console.log(formatGreeting("Bilal"));           // "Hello, Bilal!"
console.log(formatGreeting(undefined, "?"));    // "Hello, Guest?"
console.log(createPagination());                // { page: 1, pageSize: 20 }
  • Triggers on undefined only: Passing undefined (or omitting the argument) uses the default, whereas passing "", 0, false, or null keeps the passed value.
  • Works across function forms: Supported in declarations, named/anonymous expressions, arrow functions, methods, and constructors.

2. Dynamic Defaults, Left-to-Right Order, and Destructuring

Default expressions run each time the function is called—not once at definition time—and can reference earlier parameters or destructured object/array properties:

// Reference earlier parameters and supply defaults inside destructured objects
function createRange(start = 0, step = 1, end = start + step * 5) {
  return { start, step, end };
}

function connectClient({ host = "localhost", port = 5432, timeoutMs = 3000 } = {}) {
  return `${host}:${port} (${timeoutMs}ms)`;
}

// Example usage:
console.log(createRange(10, 2));          // { start: 10, step: 2, end: 20 }
console.log(connectClient());             // "localhost:5432 (3000ms)"
console.log(connectClient({ port: 6432 }));// "localhost:6432 (3000ms)"
  • Default the whole options object (= {}): Without = {} on the destructured parameter, calling connectClient() with no arguments throws a TypeError because undefined cannot be destructured.
  • Left-to-right evaluation: Later parameters can read earlier parameters, while earlier parameters cannot read later ones (doing so hits the temporal dead zone and throws a ReferenceError).

3. Caveats with null, Arguments Length, and Side Effects

Keep a few behavioral details in mind when refactoring older functions that previously checked arg === undefined or arguments.length inside the body:

// Explicit undefined vs. null behavior
function resolveLabel(label = "Untitled") {
  return label;
}

console.log(resolveLabel(undefined)); // "Untitled"
console.log(resolveLabel(null));      // null (use ?? in body if null should also fallback)
  • Handling null too: If null should also fall back to a default, use nullish coalescing (const value = param ?? fallback) inside the function body.
  • arguments.length behavior: Adding a default parameter excludes that parameter from arguments.length when called with fewer arguments, and modifying a parameter with a default value does not mutate the arguments object.

TL;DR: Write function fn(x = defaultVal) to give parameters fallback values when omitted or undefined, include = {} when destructuring optional options objects, and use ?? inside the body if null should also trigger a fallback.