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?