JavaScript tutorials > JavaScript Basics > Functions > What are default parameters in JavaScript functions?

What are default parameters in JavaScript functions?

Default parameters in JavaScript functions provide a way to set default values for function parameters if no value (or undefined) is passed when the function is called. This enhances code readability, reduces the need for verbose checks within the function body, and makes functions more resilient to missing or undefined inputs.

Basic Syntax

In this example, the greet function takes one parameter, name. We've assigned a default value of 'Guest' to name. If we call greet() without any arguments, name will default to 'Guest'. If we call greet('Alice'), the provided value 'Alice' will be used.

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

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

Concepts Behind the Snippet

The core concept is providing a fallback value for function parameters. Before default parameters, you would typically use conditional logic (if statements or the || operator) inside the function body to achieve the same effect. Default parameters offer a more concise and readable syntax.

Real-Life Use Case: Configuration Objects

This example demonstrates using default parameters with a configuration object. The createButton function accepts an optional config object. Inside the function, destructuring is used to extract properties from the config object, with default values assigned to text, color, and size. This allows for flexible button creation, where you can provide only the configurations you need, and the others will default to their pre-defined values.

function createButton(config = {}) {
  const { text = 'Click Me', color = 'blue', size = 'medium' } = config;
  console.log(`Creating a ${size} button with text '${text}' and color ${color}.`);
}

createButton(); // Output: Creating a medium button with text 'Click Me' and color blue.
createButton({ text: 'Submit', color: 'green' }); // Output: Creating a medium button with text 'Submit' and color green.
createButton({ size: 'large' }); // Output: Creating a large button with text 'Click Me' and color blue.

Best Practices

Keep it Simple: Use default parameters when a reasonable default value exists for a parameter. Avoid overusing them for complex logic.

Order Matters: Parameters with default values should generally be placed at the end of the parameter list. This is because JavaScript functions are called with positional arguments. If a parameter with a default value is not at the end, you might need to explicitly pass undefined to trigger the default value.

Interview Tip

Be prepared to discuss the advantages of default parameters over older techniques (if statements, || operator). Emphasize readability, conciseness, and maintainability. Also, understand how default parameters interact with undefined vs. null (only undefined triggers the default).

When to Use Them

Use default parameters when a function has optional arguments or when it's likely that a particular argument might be omitted. They are particularly useful when dealing with configuration objects or options that have sensible defaults.

Alternatives (Pre-ES6)

Before ES6, the || (OR) operator was commonly used to provide default values. This approach works, but it can have unexpected behavior if the parameter can have falsy values (e.g., 0, '', false). In these cases, the default value would be incorrectly used.

function greet(name) {
  name = name || 'Guest'; // Old way of providing a default value
  console.log(`Hello, ${name}!`);
}

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

Pros

  • Readability: Default parameters make the function signature more explicit about which parameters are optional and their default values.
  • Conciseness: They reduce boilerplate code within the function body.
  • Maintainability: Easier to update and modify default values in one place (the function definition).
  • Less Error-prone: Avoid potential issues with falsy values when using the old || operator approach.

Cons

  • Limited Complexity: For very complex default value computations, you might still need to use conditional logic inside the function.
  • Order Dependency: As mentioned earlier, the order of parameters matters.

Evaluation Time

The default value expression is only evaluated when the parameter is missing or undefined. In the example above, getValue() is only called when greet() is called without arguments. This can be important for performance considerations if the default value computation is expensive.

function getValue() {
  console.log('getValue() was called!');
  return 'default value';
}

function greet(name = getValue()) {
  console.log(`Hello, ${name}!`);
}

greet(); // Output: getValue() was called!
         //         Hello, default value!

greet('Bob'); // Output: Hello, Bob!

FAQ

  • What happens if I pass null as an argument to a function with a default parameter?

    If you pass null as an argument, the default value will not be used. The parameter will have the value null. Default parameters only activate when the argument is undefined or not provided.

  • Can default parameters refer to other parameters?

    Yes, default parameters can refer to other parameters that come before them in the parameter list. For example: function multiply(a, b = a * 2) { return a * b; } However, you cannot refer to parameters defined after the current parameter in the list.

  • Do default parameters create a new scope?

    No, default parameters do not create a new scope that is separate from the function's scope. They operate within the same scope as the function body.