JavaScript > ES6 and Beyond > New Syntax and Features > Default parameters

ES6 Default Parameters: Simplifying Function Arguments

This code snippet explores how to use default parameters in JavaScript ES6 functions. Default parameters allow you to set default values for function arguments if no value (or `undefined`) is passed when the function is called. This enhances code readability and reduces the need for manual checks within the function body.

Basic Syntax and Usage

This example demonstrates the basic syntax for default parameters. The `greet` function takes two parameters: `name` and `greeting`. If a value is not provided for either parameter when calling the function, the default values 'Guest' and 'Hello' will be used, respectively. When `undefined` is passed, the default value is also used.

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

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

Concepts Behind Default Parameters

Default parameters offer a cleaner way to handle optional arguments in functions. Before ES6, developers often used conditional statements (e.g., `if (typeof name === 'undefined') { name = 'Guest'; }`) to check if an argument was provided. Default parameters provide a more concise and readable syntax for achieving the same result. The default value is evaluated at the time the function is called. The default value is not a 'snapshot' taken when the function is defined. This means you can use variables or even call other functions as default values.

Real-Life Use Case Section

Imagine creating a reusable button component. You might want to provide default values for the button's text, color, and size. Default parameters make this easy. This example shows how to create a button element with default properties. This function creates a button element dynamically and sets its text, background color, and font size based on the provided arguments. If arguments are omitted, sensible defaults are used.

function createButton(text = 'Submit', color = 'blue', size = 'medium') {
  const button = document.createElement('button');
  button.textContent = text;
  button.style.backgroundColor = color;
  button.style.fontSize = size === 'large' ? '20px' : size === 'small' ? '12px' : '16px';
  document.body.appendChild(button);
  return button;
}

createButton(); // Creates a default submit button with blue color and medium size
createButton('Save', 'green'); // Creates a 'Save' button with green color and medium size

Best Practices

1. **Keep it Simple:** Use default parameters for straightforward, commonly used default values. For complex logic, consider using a separate configuration object. 2. **Order Matters:** Parameters with default values should generally be placed at the end of the parameter list. This is because arguments are passed based on their position. If you have a parameter without a default value after one *with* a default value, you'll need to explicitly pass `undefined` to use the default. 3. **Avoid Side Effects:** Avoid using default values that have side effects, such as modifying global variables or making network requests. This can make your code harder to understand and debug.

Interview Tip

Be prepared to explain how default parameters work, their benefits over older approaches, and their limitations. You should also be able to provide examples of when and how to use them effectively. A common question might be: "How do default parameters differ from checking for `undefined` inside a function?" The answer lies in cleaner syntax and better readability.

When to use them

Use default parameters when you want to provide sensible defaults for optional arguments. They're particularly useful when creating reusable functions or components. They are beneficial when you want to avoid repetitive code for handling missing or undefined arguments. They improve code readability and maintainability.

Memory Footprint

Default parameters generally don't introduce significant memory overhead. The default values are stored as part of the function definition, but they are only evaluated when the function is called without the corresponding argument. The memory impact is minimal.

Alternatives

Before ES6, developers commonly used conditional statements or logical OR operators to handle optional arguments. For example: javascript function greet(name, greeting) { name = name || 'Guest'; greeting = greeting || 'Hello'; return greeting + ', ' + name + '!'; } Another alternative is to use a configuration object: javascript function createButton(options) { const text = options.text || 'Submit'; const color = options.color || 'blue'; const size = options.size || 'medium'; // ... } However, default parameters offer a more concise and readable syntax.

Pros

  • Improved Readability: Default parameters make your code easier to understand.
  • Reduced Boilerplate: They eliminate the need for manual checks for undefined arguments.
  • Concise Syntax: They provide a more concise way to handle optional arguments.

Cons

  • Order Dependence: Parameters with default values should generally be placed at the end of the parameter list.
  • Complexity with Multiple Parameters: If you have many optional parameters, the function signature can become long and harder to read. In such cases, using a configuration object might be preferable.

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 specific value, so the parameter will take on the value `null`.
  • Can I use a function call as a default parameter?

    Yes, you can! The function call will be executed only if the corresponding argument is not provided (or is `undefined`).
  • Are default parameters supported in all browsers?

    Default parameters are a feature of ES6, so they are supported in all modern browsers. For older browsers, you may need to use a transpiler like Babel to convert your code to an older version of JavaScript.