A default value for a function parameter is set directly in the function definition using the =
operator:
function greet(name = "Guest") {
console.log("Hello,", name);
}
If name
is not passed — the value "Guest"
will be used.
undefined
when arguments are missingfunction multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5)); // 5 (b will be 1)
function createUser(name, isAdmin = false) {
return { name, isAdmin };
}
function sum(a, b = a) {
return a + b;
}
console.log(sum(3)); // 6
undefined
function fetchData(url, options = {}) {
const { method = "GET", cache = "no-cache" } = options;
// ...
}
Default parameter values are a simple and powerful tool to make your functions more robust and convenient.
Use them to write cleaner and more resilient JavaScript code.