Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Default Parameters

Default parameters let you assign fallback values when arguments are missing.

They simplify functions and reduce manual checks inside the body.

Why We Need It

Functions often accept optional inputs. Defaults make those cases clean and predictable.

They also make function signatures more self-documenting.

Syntax

function name(param = defaultValue) { ... }

Basic Example

1. Basic default

function greet(name = "Guest") {
  return "Hello " + name;
}

console.log(greet());

Missing arguments use the default value.

Real World Example

2. Number default

function addTax(price, rate = 0.18) {
  return price + price * rate;
}

console.log(addTax(100));

Defaults work with any type.

Multiple Use Cases

Provide Fallbacks

Default parameters set a value when an argument is undefined.

They reduce boilerplate checks inside your function.

Safe Configuration

Defaults are helpful for configuration objects and optional inputs.

They keep function signatures clean and easy to read.

Evaluation Rules

Default values are evaluated at call time, not at function creation time.

You can even use earlier parameters to compute defaults.

More Examples

3. Computed default

function makeId(prefix, id = prefix + "-" + Date.now()) {
  return id;
}

console.log(makeId("user"));

Defaults can depend on earlier parameters.

4. Undefined only

function label(status = "pending") {
  return status;
}

console.log(label(null)); // null, not default
console.log(label(undefined)); // uses default

Defaults only apply when the argument is undefined.

Comparison

Without

function greet(name) {
  if (name === undefined) {
    name = "Guest";
  }
  return "Hello " + name;
}

With

function greet(name = "Guest") {
  return "Hello " + name;
}

Common Mistakes and Fixes

Assuming null uses default

Defaults apply only to undefined, not null.

Overusing defaults

Use defaults for optional values, not required inputs.

Complex defaults

Keep defaults simple or move logic into the function body.

Interview Questions

When do default parameters apply?

When the argument is undefined.

Do defaults apply to null?

No, null is treated as a real value.

Can defaults be expressions?

Yes, they are evaluated at call time.

Practice Problem

Practice: Create a function that formats currency with a default symbol.

// TODO: function format(amount, symbol = "$")

One Possible Solution

function format(amount, symbol = "$") {
  return symbol + amount.toFixed(2);
}

console.log(format(10));

Frequently Asked Questions

When do defaults apply?

Only when the argument is undefined.

Can defaults reference other params?

Yes, as long as the referenced param appears earlier.

Do defaults work with destructuring?

Yes, you can provide defaults in destructured params.

Try It Yourself

Try calling the function with and without arguments.