Default parameters are a feature in JavaScript that allow you to specify default values for function parameters. This feature enhances function flexibility and reduces the need for manual parameter checking.
In JavaScript, when a function is called with fewer arguments than declared parameters, the missing arguments are set to undefined
. Default parameters provide a way to assign a default value to parameters if no argument is passed or if the argument is undefined
.
To define a default parameter, you assign a value to the parameter in the function declaration:
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
Default parameters can be more than just simple values. They can be expressions, function calls, or even other parameters:
function calculateArea(length, width = length) {
return length * width;
}
console.log(calculateArea(5)); // Output: 25
console.log(calculateArea(5, 3)); // Output: 15
function getRandomGreeting(name = "User", greeting = Math.random() > 0.5 ? "Hello" : "Hi") {
return `${greeting}, ${name}!`;
}
console.log(getRandomGreeting()); // Output: "Hello, User!" or "Hi, User!"
undefined
to trigger the default value.undefined
inside the function body.To further enhance your understanding of JavaScript functions and parameter handling, explore these related topics:
Default parameters are a powerful feature in JavaScript that can significantly improve your code's clarity and robustness. By mastering this concept, you'll write more efficient and maintainable functions in your JavaScript projects.