TypeScript Course
TypeScript
/
Beginner

Optional & Default Parameters

Definition

Optional parameters (`?`) allow you to call a function without passing all arguments. Default parameters (`= value`) automatically provide a fallback value if the argument is missing or undefined.

Explain Like I'm New

If you are ordering a burger, 'Cheese' is a required parameter. 'Bacon' is an optional parameter (`?`). If you order a 'Meal', fries are a default parameter (`= 'Fries'`); you get them automatically unless you specifically ask for a salad instead.

Real World Example

A logging function where the `level` defaults to 'INFO', but can be overridden with 'ERROR'.

Common Use Cases

  • •Flexible APIs
  • •Avoiding undefined crashes

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • Can an optional parameter come before a required parameter?

intermediate

  • Do you need to use `?` if you provide a default value?

advanced

  • How does TS infer the type of a default parameter?

Flash Cards

Question

Can an optional parameter come first?

Click to reveal answer
Answer

No. In TypeScript, all required parameters MUST come before optional parameters. If `function(a?, b)` was allowed, calling `func(5)` would be ambiguous—is 5 meant for 'a' or 'b'?

Question

Do you need '?' if you provide a default?

Click to reveal answer
Answer

No. If you write `msg = 'Hello'`, TypeScript automatically knows two things: 1. It is a string. 2. It is optional. Writing `msg?: string = 'Hello'` is redundant and generally disallowed.