Default Parameters
In this page:
Basic Default Values
Assigning a value directly to a parameter, like (retries: number = 3), makes that value the default used whenever the caller omits an argument for it. Unlike a manually written if (x === undefined) check, this default is enforced right in the function signature.
Example: Basic Default Values
function connect(retries: number = 3) {
console.log(`Connecting with ${retries} retries`);
}
connect();
Overriding Default Values
A caller can still provide their own argument to override the default value at any time, simply by passing something explicitly in that position. The default only kicks in when the argument is left out or passed as undefined.
Example: Overriding Default Values
function connect(retries: number = 3) {
console.log(`Connecting with ${retries} retries`);
}
connect(5);
Multiple Default Parameters
A single function can have more than one parameter with its own default value, each independent of the others. This lets a function offer several sensible fallbacks while still accepting full customization when a caller needs it.
Example: Multiple Default Parameters
function createUser(name: string = "Guest", role: string = "member") {
console.log(name, role);
}
createUser();
createUser("Priya");
Default Parameters with Expressions
A default value doesn't have to be a literal; it can be calculated from an expression, and that expression is evaluated fresh every time the function is called without that argument. This is handy for defaults that depend on other parameters or a shared constant.
Example: Default Parameters with Expressions
function logEvent(message: string, time: string = new Date().toISOString()) {
console.log(message, time);
}
logEvent("Started");
Default Parameters vs Optional Parameters
Optional parameters can end up undefined inside the function body, while default parameters automatically receive their fallback value the moment the argument is omitted. This means default parameters never need the manual undefined check that optional parameters often do.
Example: Default Parameters vs Optional Parameters
function withDefault(x: number = 10) {
console.log(x); // always a number
}
function withOptional(x?: number) {
console.log(x); // number | undefined
}
withDefault();
withOptional();
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: