Default Parameters in Functions

Imagine you’re making a sandwich and you have a default way of making it unless someone asks for something different. That’s kind of how default parameters work in JavaScript functions.

Before this feature was added to JavaScript, if you didn’t provide all the ingredients (or parameters) for your function (or sandwich), you might end up with something unexpected. Now, with default parameters, you can set a standard ingredient that your function will use unless you tell it otherwise.

What Are Default Parameters?

Default parameters allow functions to have pre-set values for their parameters. These default values kick in when the function is called without those parameters, or when undefined is passed. This feature helps prevent errors in your code when arguments are not provided, and also makes your functions more readable and manageable.

Basic Usage

Let’s say we have a function that greets a user. We can set a default name in case one isn’t provided:

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

greet("Alice"); // Outputs: Hello, Alice!
greet();        // Outputs: Hello, Guest!

Here, if we don’t provide a name, our function uses "Guest" as the default name.

Why Use Default Parameters?

Without default parameters, handling missing arguments could get a bit tricky. You might need to use an if statement or the logical OR operator (||) to assign a default value inside the function:

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

While this works, it’s not as clean or clear as using a default parameter. It also can lead to unexpected results with falsy values.

Advanced Example

Default parameters can be more than just simple values; they can also be expressions or even other functions:

function getDefaultName() {
  return "Guest";
}

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

This approach is super flexible, allowing your default values to be dynamically determined.

Combining with Destructuring

Default parameters become even more powerful when combined with destructuring. This is great for functions that take configuration objects:

function setup({width = 100, height = 100, color = "black"} = {}) {
  console.log(`Width: ${width}, Height: ${height}, Color: ${color}`);
}

setup({width: 200}); // Width: 200, Height: 100, Color: black
setup();             // Width: 100, Height: 100, Color: black

In the second call to setup(), we don’t pass any arguments, so it uses all the default values.

Conclusion

Default parameters make function parameters flexible and error-resistant, providing a fallback value that ensures your functions always have the data they need to run correctly. Whether it’s a simple value, the result of an expression, or even another function, default parameters help keep your JavaScript code clean and understandable.