Skip to main content

JavaScript Default Parameters

Introduction

When building applications with JavaScript, you'll often create functions that need to handle different types of inputs. Sometimes, you might want to make certain parameters optional or provide default values when the caller doesn't specify them. Before ES6 (ECMAScript 2015), developers had to write extra code within functions to handle missing arguments, but now JavaScript provides a cleaner solution: default parameters.

Default parameters allow you to specify default values for function parameters when no value or undefined is passed. This feature makes your code more concise, readable, and less prone to errors.

Basic Syntax

Here's the basic syntax for defining default parameters in a function:

javascript
function functionName(parameter1 = defaultValue1, parameter2 = defaultValue2) {
// function body
}

How Default Parameters Work

Let's explore how default parameters work with simple examples:

Example 1: A Simple Greeting Function

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

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

In this example, if no argument is provided when calling the greet() function, the default value "Guest" is used for the name parameter.

Example 2: Multiple Default Parameters

You can define default values for multiple parameters:

javascript
function createUser(username = "anonymous", age = 0, isPremium = false) {
return {
username,
age,
accountType: isPremium ? "Premium" : "Basic"
};
}

// All parameters provided
console.log(createUser("alex123", 28, true));
// Output: { username: "alex123", age: 28, accountType: "Premium" }

// Only first parameter provided
console.log(createUser("jenny99"));
// Output: { username: "jenny99", age: 0, accountType: "Basic" }

// No parameters provided
console.log(createUser());
// Output: { username: "anonymous", age: 0, accountType: "Basic" }

Important Behaviors to Understand

1. Only undefined Triggers Default Values

Default parameters are only applied when the argument is undefined or not provided:

javascript
function test(a = 1, b = 2) {
return [a, b];
}

console.log(test(5, 6)); // Output: [5, 6]
console.log(test(5)); // Output: [5, 2]
console.log(test()); // Output: [1, 2]
console.log(test(undefined)); // Output: [1, 2]
console.log(test(null)); // Output: [null, 2] - null is a valid value!
console.log(test(0, '')); // Output: [0, ''] - 0 and '' are valid values

2. Using Expressions as Default Values

Default parameters can be expressions, not just static values:

javascript
function calculateTax(price, taxRate = 0.1, currentDate = new Date()) {
console.log(`Tax calculation performed on: ${currentDate}`);
return price * taxRate;
}

console.log(calculateTax(100));
// Output:
// Tax calculation performed on: [current date and time]
// 10

3. Using Previous Parameters in Default Values

You can use the value of previous parameters to define defaults for later parameters:

javascript
function calculateRectangleArea(width, height = width) {
return width * height;
}

console.log(calculateRectangleArea(5, 10)); // Output: 50
console.log(calculateRectangleArea(5)); // Output: 25 (creates a square)

Common Use Cases

1. API Configuration

Default parameters are extremely useful for configuring API calls:

javascript
function fetchData(url, method = "GET", headers = {
"Content-Type": "application/json"
}, timeout = 5000) {
console.log(`Making ${method} request to ${url}`);
console.log(`Headers: ${JSON.stringify(headers)}`);
console.log(`Timeout set to ${timeout}ms`);
// Actual fetch logic would go here
}

// Use with minimal configuration
fetchData("https://api.example.com/users");
// Output:
// Making GET request to https://api.example.com/users
// Headers: {"Content-Type":"application/json"}
// Timeout set to 5000ms

// Override some defaults
fetchData("https://api.example.com/posts", "POST");
// Output:
// Making POST request to https://api.example.com/posts
// Headers: {"Content-Type":"application/json"}
// Timeout set to 5000ms

2. UI Component Configuration

Default parameters help create flexible UI components that can be customized as needed:

javascript
function createButton(text = "Click Me", color = "blue", size = "medium", onClick = () => console.log("Button clicked!")) {
const button = document.createElement("button");
button.textContent = text;
button.style.backgroundColor = color;
button.classList.add(`btn-${size}`);
button.addEventListener("click", onClick);
return button;
}

// Create a default button
const defaultButton = createButton();

// Create a customized button
const submitButton = createButton("Submit", "green", "large", () => {
console.log("Form submitted!");
});

3. Math Functions

Default parameters are helpful for mathematical functions that have common default values:

javascript
function calculateCircleArea(radius, pi = Math.PI) {
return pi * radius * radius;
}

console.log(calculateCircleArea(5)); // Uses Math.PI
console.log(calculateCircleArea(5, 3.14)); // Uses 3.14 for pi

Best Practices

1. Place Parameters with Default Values Last

For better readability and to avoid confusion, place parameters with default values at the end of the parameter list:

javascript
// Good practice
function createProfile(username, email, isPremium = false, joinDate = new Date()) {
// function body
}

// Harder to use - avoid this pattern
function createProfile(username = "anonymous", email, isPremium = false) {
// You'll need to pass undefined to use the default username
// but provide a specific email
}

2. Avoid Side Effects in Default Parameter Expressions

When using expressions as default values, avoid complex operations that might cause side effects:

javascript
// Avoid this pattern
let counter = 0;
function incrementCounter(step = counter++) {
return step;
}

// Better approach
function incrementCounter(step = 1) {
counter += step;
return counter;
}

3. Consider Using Object Parameter for Complex Functions

For functions with many parameters, consider using an object parameter with defaults:

javascript
function configureDashboard({
theme = "light",
sidebar = true,
notifications = true,
language = "en"
} = {}) {
// The = {} at the end ensures the function can be called with no arguments
return { theme, sidebar, notifications, language };
}

// Use with default values
console.log(configureDashboard());
// { theme: "light", sidebar: true, notifications: true, language: "en" }

// Override specific properties
console.log(configureDashboard({ theme: "dark", language: "fr" }));
// { theme: "dark", sidebar: true, notifications: true, language: "fr" }

Compatibility Note

Default parameters are an ES6 feature and are supported in all modern browsers. However, if you need to support older browsers, you might need to use a transpiler like Babel or consider using the older pattern:

javascript
// Old way (pre-ES6)
function greet(name) {
name = name !== undefined ? name : "Guest";
return "Hello, " + name + "!";
}

// Modern way (ES6+)
function greet(name = "Guest") {
return `Hello, ${name}!`;
}

Summary

Default parameters in JavaScript provide a clean and efficient way to handle optional function arguments. They make your code more readable, robust, and maintainable by:

  • Reducing boilerplate code for handling missing arguments
  • Making function interfaces more explicit
  • Supporting expressions and dynamic values as defaults
  • Working seamlessly with other JavaScript features

By understanding and using default parameters effectively, you can write more elegant and flexible JavaScript functions that handle a variety of input scenarios gracefully.

Practice Exercises

  1. Create a function called formatCurrency that formats a number as currency. Use default parameters to specify the currency symbol, decimal places, and locale.

  2. Build a function that creates DOM elements with various configurable properties using default parameters.

  3. Write a function called fetchUserProfile that simulates fetching user data with configurable options for what fields to include, whether to include nested data, etc.

Additional Resources

Happy coding with default parameters!



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