What are Optional Parameters?
Optional parameters allow you to define function parameters that may or may not be provided when the function is called.
Optional Parameter Syntax
TypeScriptRead-only
1
Default Parameters
Default parameters assign a default value when no argument is passed.
TypeScriptRead-only
1
Optional vs Default
| Feature | Optional | Default |
|---|---|---|
| Value Required | No | No |
| Default Value | No | Yes |
| Usage | Flexible input | Predefined fallback |
Combining Both
TypeScriptRead-only
1
Parameter Order Rules
Optional parameters must come after required parameters, while default parameters can be placed flexibly but should follow best practices.
Best Practices
- Place optional parameters at the end
- Use default values for predictable behavior
- Avoid too many optional parameters
- Keep function signatures simple
Common Mistakes
- Wrong parameter order
- Confusing optional with default
- Overusing optional parameters
- Not handling undefined values properly
Conclusion
Optional and default parameters improve flexibility in TypeScript functions while maintaining clarity and type safety.