Skip to main content

JavaScript Default Parameters

Introduction

When writing functions in JavaScript, there are times when you want certain parameters to have default values if no argument is provided during function calls. Before ES6 (ECMAScript 2015), developers had to use workarounds to implement this behavior. Now, JavaScript natively supports default parameters, making your code cleaner and more intuitive.

Default parameters allow you to specify fallback values for function parameters that are undefined or not passed to the function. This feature reduces the need for conditional checks inside functions and makes your code more readable and maintainable.

Basic Syntax

Here's the basic syntax for using default parameters in JavaScript:

javascript
function functionName(param1 = defaultValue1, param2 = defaultValue2) {
// function body
}

Let's see how this works with a simple example:

javascript
function greet(name = "Guest") {
return `Hello, ${name}!`;
}

console.log(greet("John")); // Output: Hello, John!
console.log(greet()); // Output: Hello, Guest!

In this example, when we call greet() without any arguments, the parameter name takes the default value "Guest". When an argument is provided, the default value is ignored.

How Default Parameters Work

Default parameters are only used when the argument is:

  • Not provided (undefined)
  • Explicitly set to undefined

Let's clarify with examples:

javascript
function displayInfo(name = "Unknown", age = 0) {
return `Name: ${name}, Age: ${age}`;
}

console.log(displayInfo("Alice", 25)); // Output: Name: Alice, Age: 25
console.log(displayInfo("Bob")); // Output: Name: Bob, Age: 0
console.log(displayInfo()); // Output: Name: Unknown, Age: 0
console.log(displayInfo(undefined, 30)); // Output: Name: Unknown, Age: 30
console.log(displayInfo(null, 30)); // Output: Name: null, Age: 30

Note that null is considered a valid value, so default values won't be used when null is passed.

Advanced Usage

Expressions as Default Values

Default parameters can be expressions, not just static values:

javascript
function generateId(prefix = "user", timestamp = Date.now()) {
return `${prefix}_${timestamp}`;
}

console.log(generateId()); // Output: user_1631234567890 (timestamp will vary)
console.log(generateId("admin")); // Output: admin_1631234567890 (timestamp will vary)

Using Previous Parameters

Default parameters can use values from parameters declared earlier in the parameter list:

javascript
function createRect(width = 10, height = width * 2) {
return { width, height, area: width * height };
}

console.log(createRect(5)); // Output: { width: 5, height: 10, area: 50 }
console.log(createRect()); // Output: { width: 10, height: 20, area: 200 }

In this example, if height is not provided, it's calculated using the width parameter.

Function Calls as Default Parameters

You can even use function calls as default parameter values:

javascript
function getDefaultName() {
return "Anonymous_" + Math.floor(Math.random() * 1000);
}

function registerUser(name = getDefaultName(), role = "user") {
return `Registered: ${name} as ${role}`;
}

console.log(registerUser("Jane", "admin")); // Output: Registered: Jane as admin
console.log(registerUser()); // Output: Registered: Anonymous_123 as user (number will vary)

Real-World Applications

API Function with Configuration Options

javascript
function fetchData(url, options = { method: 'GET', headers: { 'Content-Type': 'application/json' } }) {
console.log(`Fetching ${url} with method: ${options.method}`);
// Actual fetch implementation would go here
}

fetchData('https://api.example.com/data');
// Output: Fetching https://api.example.com/data with method: GET

fetchData('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// Output: Fetching https://api.example.com/data with method: POST

UI Component Configuration

javascript
function createButton(text = "Click Me", { color = "blue", size = "medium", disabled = false } = {}) {
return `
<button
style="background-color: ${color}; font-size: ${sizeToPixels(size)}px;"
${disabled ? 'disabled' : ''}
>
${text}
</button>
`;

function sizeToPixels(size) {
const sizes = { small: 12, medium: 16, large: 20 };
return sizes[size] || sizes.medium;
}
}

console.log(createButton());
// Output: A blue medium-sized button with "Click Me" text

console.log(createButton("Submit", { color: "green", size: "large" }));
// Output: A green large-sized button with "Submit" text

Format Currency with Options

javascript
function formatCurrency(amount, { currency = "USD", locale = "en-US", decimals = 2 } = {}) {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency,
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
}).format(amount);
}

console.log(formatCurrency(1234.56));
// Output: $1,234.56

console.log(formatCurrency(1234.56, { currency: "EUR", locale: "de-DE" }));
// Output: 1.234,56 €

console.log(formatCurrency(1234.56, { decimals: 0 }));
// Output: $1,235

Common Pitfalls and Best Practices

Default Parameters with Object Destructuring

When using object destructuring with default parameters, remember to provide a default empty object:

javascript
// Bad approach - will throw error if options is undefined
function badConfig({ name, age }) {
console.log(`Name: ${name}, Age: ${age}`);
}

// Good approach - provides default empty object
function goodConfig({ name = "Unknown", age = 0 } = {}) {
console.log(`Name: ${name}, Age: ${age}`);
}

goodConfig(); // Output: Name: Unknown, Age: 0

TDZ (Temporal Dead Zone) Issues

Be careful when referencing parameters that haven't been initialized yet:

javascript
// This will cause an error
function broken(a = b, b = 1) {
return [a, b];
}

// This works fine
function working(a = 1, b = a) {
return [a, b];
}

console.log(working()); // Output: [1, 1]
console.log(working(5)); // Output: [5, 5]

Summary

Default parameters in JavaScript provide a clean, concise way to handle optional function arguments. They help you:

  • Write more robust code with fewer conditional statements
  • Make your function APIs clearer and more intuitive
  • Handle common cases automatically while still allowing customization

By using default parameters effectively, you can create more flexible, maintainable functions that adapt to different use cases without unnecessary complexity.

Exercises

  1. Create a function createUser with default parameters that builds a user object with properties for name, age, and role.
  2. Write a function that calculates discounted prices with default parameters for discount percentage and tax rate.
  3. Implement a logging function with default parameters that include timestamps and log levels.
  4. Create a function to generate HTML elements with default styling parameters.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)