Default Parameters

Give function parameters fallback values.

Syntaxfunction f(x = 1, y = x * 2) { ... }

Default parameters let a function use a fallback value when an argument is missing. Set them with = in the parameter list.

Any expression

Defaults can be any expression, and can even use earlier parameters.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Allow callers to omit a page size argument and fall back to 10 results per page by default.
  • Provide a default log level of 'info' so the logger works without requiring explicit configuration.
  • Set a default currency of 'USD' in a price formatter to handle the most common case concisely.

More examples

Basic default parameter

Defines a default greeting that is used when the second argument is omitted by the caller.

Example · js
function greet(name, greeting = "Hello") {
  return `${greeting}, ${name}!`;
}
console.log(greet("Alice"));          // "Hello, Alice!"
console.log(greet("Bob", "Hi"));      // "Hi, Bob!"

Default from another parameter

Uses an earlier parameter in the default expression for a later one.

Example · js
function createRange(start, end = start + 10) {
  return { start, end };
}
console.log(createRange(5));     // { start: 5, end: 15 }
console.log(createRange(5, 20)); // { start: 5, end: 20 }

Default object parameter

Defaults the options parameter to an empty object so callers can safely omit it without a TypeError.

Example · js
function request(url, options = {}) {
  const method = options.method ?? "GET";
  console.log(method, url);
}
request("/api/users");               // GET /api/users
request("/api/posts", { method: "POST" }); // POST /api/posts

Discussion

  • Be the first to comment on this lesson.
Default Parameters — JavaScript | SoundsCode