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
// OPTIONAL PARAMETER (?) function buildName(first: string, last?: string) { if (last) return `${first} ${last}`; return first; } console.log(buildName("Alice")); // Valid! console.log(buildName("Alice", "Smith")); // Valid! // DEFAULT PARAMETER (=) function createGreeting(name: string, greeting: string = "Hello") { return `${greeting}, ${name}`; } console.log(createGreeting("Bob")); // "Hello, Bob" console.log(createGreeting("Bob", "Welcome")); // "Welcome, Bob"
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?