Course contentsShow
← JavaScript
Lesson 409 of 2,72311. FunctionsFree lesson

Default Parameters Can Reference Earlier Parameters

Learn how default values can use previously declared parameters in their expressions.

Default Parameters Can Reference Earlier Parameters

What you'll learn: You'll discover that a default parameter value can use the value of a parameter that was declared before it.

When you define multiple parameters with default values, JavaScript evaluates them from left to right. This means later parameters can reference earlier ones in their default expressions — they're already available in that scope.

function greet(name = "Guest", message = `Welcome, ${name}!`) {
  console.log(message);
}

greet("Alice");  // "Welcome, Alice!"
greet();         // "Welcome, Guest!"

In the example above, the message parameter's default value uses name. When you call greet("Alice"), name becomes "Alice", and message uses that value in its default expression.

Why This Works

Parameters are initialized in the order they appear, creating a left-to-right scope. By the time JavaScript evaluates message's default, name already exists and has a value (either passed in or its own default).

function calculatePrice(basePrice = 100, tax = basePrice * 0.1) {
  return basePrice + tax;
}

calculatePrice(200);  // 220 (200 + 20)
calculatePrice();     // 110 (100 + 10)

Important Limitation

You cannot reference later parameters from earlier ones — they don't exist yet:

// ❌ This will cause an error
function broken(first = second, second = 10) {
  return first + second;
}

Think of it like reading a book: you can reference what you've already read, but not what's on the next page.

Key Takeaway: Default parameter expressions are evaluated left to right, so later parameters can reference earlier parameters in their default values, but not vice versa.