Default parameters
What it is
Default parameters let you set a value for a function parameter right in its definition, which is used when that argument is missing at the call site or equals
undefined.
Example without default parameters
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // Hello, Alice!
greet(); // Hello, undefined!If the argument is not passed, name equals undefined.
Example with a default parameter
function greet(name = "guest") {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // Hello, Alice!
greet(); // Hello, guest!Now, if the argument is not passed,
the function takes the default value "guest".
How it works
A default parameter kicks in if the argument:
- is not passed at all, or
- is explicitly equal to
undefined
function test(a = 10) {
console.log(a);
}
test(); // 10 (no argument)
test(undefined); // 10 (explicit undefined)
test(null); // null (not undefined!)Expressions and functions can be used
The default value does not have to be a constant, it can be any expression, even a call to another function.
function getRandom() {
return Math.floor(Math.random() * 10);
}
function printNumber(n = getRandom()) {
console.log(n);
}
printNumber(); // random number from 0 to 9
printNumber(7); // 7Order and combining
Default parameters can be set in any order, but most often go at the end of the argument list.
function info(name, age = 18, city = "Kyiv") {
console.log(`${name}, ${age} years old, from ${city}`);
}
info("Alice"); // Alice, 18 years old, from Kyiv
info("Bob", 25, "Lviv"); // Bob, 25 years old, from LvivIf you skip a value that is not at the end, you must explicitly pass undefined:
info("Oleh", undefined, "Warsaw");
// Oleh, 18 years old, from WarsawOther parameters can be used as default values
function sum(a, b = a) {
return a + b;
}
console.log(sum(5)); // 10
console.log(sum(5, 2)); // 7Difference from the old approach (pre-ES6)
Previously, programmers wrote an "emulation" using ||:
function greet(name) {
name = name || "guest";
console.log(`Hello, ${name}!`);
}But this had a drawback:
greet(""); // Hello, guest! - even though the string is empty, not undefinedDefault parameters are better because they only kick in for undefined,
not for "falsy" values like 0, "" or false.
Remember in short
| Property | Description |
|---|---|
| When it kicks in | If the argument is not passed or equals undefined |
| Value type | Any expression, number, string, function, etc. |
| Can reference previous parameters | Yes |
| Works in arrow functions | Yes |
Does not replace null, 0, '' | No, they count as passed values |
Example to remember
function connect(host = "localhost", port = 3000) {
console.log(`Connecting to ${host}:${port}`);
}
connect(); // localhost:3000
connect("api.example.com"); // api.example.com:3000
connect("api.example.com", 8080); // api.example.com:8080Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.