capypad
0 day streak
typescript / beginner
Snippet

Optional Function Parameters

Function parameters can be marked as optional using the question mark syntax, allowing them to be omitted during calls.

snippet.ts
typescript
1
2
3
function greet(name: string, title?: string) {
return "Hello " + (title ? title + " " : "") + name;
}
Breakdown
1
title?: string
The 'title' parameter is optional; its value will be undefined if not provided.
2
(title ? title + " " : "")
A ternary operator checks if title exists before using it in the string.