Default Parameters in JavaScript: What They Are and How to Use Them
default parameters allow you to set a default value for a function parameter if no argument or undefined is passed. This helps avoid errors and makes functions easier to use by providing fallback values automatically.How It Works
Imagine you are baking cookies and the recipe says to add sugar, but sometimes you forget to add it. Default parameters in JavaScript work like a recipe that already includes a set amount of sugar if you forget to add it yourself.
When you define a function, you can assign a default value to its parameters. If the caller does not provide a value or passes undefined, JavaScript uses the default value instead. This means your function always has a value to work with, preventing unexpected errors or the need to write extra code to check for missing inputs.
Example
This example shows a function that greets a person. If no name is given, it uses "Guest" as the default.
function greet(name = "Guest") { return `Hello, ${name}!`; } console.log(greet("Alice")); console.log(greet());
When to Use
Use default parameters when you want your functions to work smoothly even if some arguments are missing. This is common in settings where users might not provide all inputs, like configuration options or personalized messages.
For example, if you build a function to calculate discounts, you can set a default discount rate so the function still works if the user doesn't specify one. This reduces bugs and makes your code cleaner and easier to maintain.
Key Points
- Default parameters provide fallback values for function arguments.
- They activate only if the argument is missing or
undefined. - They simplify code by removing the need for manual checks inside functions.
- They improve function usability and reduce errors.