← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 7 of 10

Default Parameters

Default parameters provide a value automatically when an argument is not supplied. They make functions easier to call while still allowing callers to provide custom values.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
function withDefault(x: number = 10) {
  console.log(x); // always a number
}
function withOptional(x?: number) {
  console.log(x); // number | undefined
}
withDefault();
withOptional();

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.