JavaScript > Functions > Function Parameters and Arguments > Default parameters

JavaScript Default Parameters: Simplifying Function Calls

Learn how to use default parameters in JavaScript functions to make your code more readable and robust. This snippet provides a comprehensive guide with examples, best practices, and common use cases.

Basic Default Parameter Example

This example demonstrates the basic syntax for default parameters. If no argument is provided when calling the `greet` function, the `name` parameter defaults to 'Guest'.

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

console.log(greet('Alice'));   // Output: Hello, Alice!
console.log(greet());        // Output: Hello, Guest!

Explanation of Default Parameters

Default parameters allow you to specify default values for function parameters. These default values are used when the corresponding argument is omitted or passed as `undefined` during the function call. This provides a fallback mechanism ensuring your function can handle missing or undefined inputs gracefully. This increases the resilience of your code.

Default Parameters with Complex Logic

This example shows how default parameters can depend on other parameters. In this case, `height` defaults to the value of `width` if no explicit `height` argument is provided. Note that default parameters are evaluated at call time.

function calculateArea(width = 1, height = width) {
  return width * height;
}

console.log(calculateArea(5, 10));  // Output: 50
console.log(calculateArea(5));     // Output: 25 (height defaults to width, which is 5)
console.log(calculateArea());    // Output: 1 (width defaults to 1, height defaults to width which is 1)

Using Functions as Default Parameters

You can also use functions as default parameters. The function will only be called if the corresponding argument is not provided or is `undefined`. This allows for dynamic default values.

function getDefaultValue() {
  console.log('getDefaultValue() called');
  return 10;
}

function multiply(a, b = getDefaultValue()) {
  return a * b;
}

console.log(multiply(5)); // Output: getDefaultValue() called, 50
console.log(multiply(5, 2)); // Output: 10

Real-Life Use Case: API Request with Optional Parameters

A common use case is in functions that make API requests. The `options` parameter, which often includes the HTTP method, headers, and body, can have a default value. This allows users to call the function with only the URL if they want to use the default options. This makes your API calls cleaner and more flexible. Remember to handle potential errors using `try...catch`.

async function fetchData(url, options = { method: 'GET' }) {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

// Usage:
fetchData('https://api.example.com/data') // Uses default GET method
  .then(data => console.log(data));

fetchData('https://api.example.com/data', { method: 'POST', body: JSON.stringify({ key: 'value' }) })
  .then(data => console.log(data));

Best Practices

  • Always place parameters with default values at the end of the parameter list. This improves readability and avoids unexpected behavior when calling the function.
  • Avoid using mutable objects as default parameter values. Each time the function is called without the parameter, the same mutable object is used, which can lead to unexpected side effects.
  • Use default parameters to provide sensible defaults and improve the robustness of your code.

Interview Tip

Be prepared to explain how default parameters work, their advantages (e.g., improved readability, reduced boilerplate), and potential pitfalls (e.g., interaction with the arguments object in older JavaScript versions, using mutable default values). Demonstrate your understanding with examples.

When to use them

Use default parameters when you want to provide a fallback value for a function parameter if the caller doesn't provide one. This simplifies function calls and makes your code more resilient to missing or undefined inputs. They are especially useful when creating reusable components or libraries.

Memory Footprint

The memory footprint of default parameters is generally negligible. The default values are stored with the function definition, and only used if the corresponding argument is not provided. The memory used to store the default value is generally small, especially for primitive values like numbers or strings.

Alternatives

Before default parameters were introduced in ES6, developers commonly used the following pattern to achieve similar functionality:

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

However, default parameters are now the preferred and more readable way to handle optional parameters.

Pros

  • Improved readability: Makes function signatures clearer and easier to understand.
  • Reduced boilerplate: Eliminates the need to manually check for undefined parameters.
  • Increased robustness: Provides a fallback mechanism for missing or undefined inputs.

Cons

  • Can be less flexible than using configuration objects when dealing with a large number of optional parameters.
  • Requires ES6+ support.

FAQ

  • What happens if I pass `null` as an argument when a default parameter is defined?

    If you pass `null` as an argument, the default value will not be used. `null` is a valid value, and it will override the default parameter.
  • Can I use expressions or function calls as default parameter values?

    Yes, you can use expressions or function calls as default parameter values. They are evaluated at call time, meaning the function is executed only when the parameter is omitted or undefined.
  • Are default parameters supported in all browsers?

    Default parameters are part of ES6 and are supported in all modern browsers. For older browsers, you may need to use a transpiler like Babel to convert your code to ES5.