We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Default Parameters

Default parameters provide fallback values for arguments that callers can omit.

function newCharacter(name: string, role: string = "warrior"): string {
  return `${name} is a ${role}`;
}

console.log(newCharacter("Gandalf"));
// Gandalf is a warrior
console.log(newCharacter("Gandalf", "wizard"));
// Gandalf is a wizard

When you use default parameters, you do not need to mark the parameter as optional by using ?. When using a default value, the parameter type can be automatically inferred, so don't specify it:

function countdown(start = 10): void {
  // start is a number
  console.log(`Counting down from ${start}...`);
}

...well, unless you need to widen the type.

Assignment

Support.ai is improving its response time estimation system. The team needs to accurately communicate to users how long their AI requests will take to process.

    • promptLength (a number) with a default value of 100 tokens.
    • modelType (a string) with a default value of text.
    • text: 2 + (0.01 * promptLength) seconds
    • image: 5 + (0.02 * promptLength) seconds
    • code: 3 + (0.05 * promptLength) seconds
    • anything else: 0 seconds

Tip

The Math.round function can be used to round a number to the nearest whole number.

console.log(Math.round(3.6));
// 4