JavaScript Default Parameters


JavaScript functions allow you to define default values for parameters. This feature, introduced in ES6 (ECMAScript 2015), helps prevent bugs when parameters are not provided and ensures that functions behave as expected. Default parameters provide a way to specify initial values for function arguments, making code more robust and reducing the need for manual checks.


1. What Are Default Parameters in JavaScript?

A default parameter is a way to assign a default value to a function parameter if no value or undefined is passed to the function. This helps ensure that a parameter always has a value, making your functions more predictable and reducing the need for conditional checks inside the function body.

Syntax of Default Parameters

The basic syntax for default parameters is:

function functionName(parameter = defaultValue) {
  // function body
}
  • parameter: The parameter that you want to assign a default value to.
  • defaultValue: The value that will be assigned to the parameter if no value or undefined is passed when calling the function.

2. Example: Default Parameters in Action

Let’s look at a basic example to understand how default parameters work.

Example: Function with Default Parameter

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

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

In this example:

  • When we call greet('Alice'), the value 'Alice' is passed and used as the argument.
  • When we call greet() with no argument, the default value 'Guest' is used.

3. Why Use Default Parameters?

Default parameters improve the readability and maintainability of code by reducing the need for additional conditional statements or manual checks for undefined values. Without default parameters, you might have to write code like this:

Without Default Parameters

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

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

As you can see, default parameters eliminate the need for the if check, making the code cleaner and easier to understand.


4. Default Parameters with Multiple Arguments

You can also use default parameters when your function has multiple parameters. Each parameter can have its own default value, making it flexible for different use cases.

Example: Multiple Default Parameters

function createProfile(name = 'Anonymous', age = 18, country = 'Unknown') {
  console.log(`Name: ${name}, Age: ${age}, Country: ${country}`);
}

createProfile();  // Output: Name: Anonymous, Age: 18, Country: Unknown
createProfile('John', 30);  // Output: Name: John, Age: 30, Country: Unknown
createProfile('Alice', 25, 'USA');  // Output: Name: Alice, Age: 25, Country: USA

In this example:

  • If no arguments are passed, all parameters take their default values.
  • If only some arguments are passed, the remaining ones take their default values.

5. Default Parameters and undefined

It's important to note that default parameters only kick in when undefined is passed or no value is passed at all. If a function argument is explicitly passed as null, it will not trigger the default value.

Example: Default Parameters and null

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

greet(null);  // Output: Hello, null!
greet();      // Output: Hello, Guest!

In this example, when null is passed, the function uses null as the value instead of the default value 'Guest'. Default parameters only apply when the value is undefined, not when it's explicitly set to null.


6. Using Expressions for Default Values

You can also use expressions as default values. This allows for more dynamic defaults based on conditions, calculations, or function calls.

Example: Expressions as Default Values

function calculateTotal(price, tax = price * 0.05) {
  console.log(`Total Price: $${price + tax}`);
}

calculateTotal(100);       // Output: Total Price: $105
calculateTotal(100, 20);   // Output: Total Price: $120

In this example:

  • If the tax parameter is not passed, it defaults to 5% of the price.
  • If a value for tax is passed, the default is overridden.

7. Default Parameters with Destructuring

Default parameters can also be used with object or array destructuring, allowing you to set default values for destructured variables.

Example: Default Parameters with Object Destructuring

function displayPerson({ name = 'John Doe', age = 30 }) {
  console.log(`Name: ${name}, Age: ${age}`);
}

displayPerson({});          // Output: Name: John Doe, Age: 30
displayPerson({ name: 'Alice' }); // Output: Name: Alice, Age: 30

In this example:

  • If the name or age properties are missing from the object, the default values are used.
  • This is particularly useful when working with functions that expect objects with specific properties.

8. Using Default Parameters in Arrow Functions

Arrow functions, just like traditional functions, also support default parameters. The syntax remains the same.

Example: Default Parameters in Arrow Functions

const multiply = (a, b = 2) => a * b;

console.log(multiply(3));  // Output: 6 (3 * 2)
console.log(multiply(3, 4));  // Output: 12 (3 * 4)

Here, the b parameter has a default value of 2. If only one argument is passed, the second argument defaults to 2.


9. Combining Default Parameters with Rest Parameters

JavaScript allows you to combine default parameters with rest parameters to create flexible and powerful functions.

Example: Default Parameters and Rest Parameters

function sum(base, ...numbers) {
  const total = numbers.reduce((acc, num) => acc + num, base);
  return total;
}

console.log(sum(10, 1, 2, 3));  // Output: 16 (10 + 1 + 2 + 3)
console.log(sum(10));           // Output: 10 (just the base value)

In this example:

  • The base parameter has no default value, but the numbers parameter uses rest parameters to collect any remaining arguments.
  • The default value for base is handled by adding additional logic in the function.