AI Hints
TypeScript · Lesson 15 of 120

Optional and Default Parameters

Flexible calls.

⏱ 2 min read▶ Video at 12:32🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Some parameters aren't always needed. A question mark makes a parameter optional. An equals sign gives it a default value.

Optional and Default Parameters
From the video: Optional and Default Parameters
  • Not always needed
  • ? optional
  • = default

Optional and default

Greet has an optional title, and a default greeting of hello. Inside, title might be undefined, so we check it. Run it. Each call fills in what's missing.

app.tstypescript
function greet(name: string, title?: string, greeting = "Hello") {
  const who = title ? `${title} ${name}` : name;
  return `${greeting}, ${who}!`;
}

console.log(greet("Priya"));
console.log(greet("Patel", "Dr"));
console.log(greet("Sam", undefined, "Welcome back"));
Output
Hello, Priya!
Hello, Dr Patel!
Welcome back, Sam!

Rules

Optional parameters come after required ones. A default value also makes a parameter optional. And its type is inferred from the default.

keyvalue
Orderrequired first
title?may be undefined
greeting = 'Hello'optional too
Typefrom the default

Summary

Use a question mark for optional parameters, and equals for defaults. Next, rest parameters.

Key takeaways
  • title?
  • = default
  • Required first
Next up: Rest Parameters — many arguments