Ad space (banner)
Lesson 6 / 20

Optional Parameters and Default Parameters

This lesson covers parameters that can be omitted (optional parameters) and parameters with a built-in initial value (default parameters). It's for anyone searching "TypeScript optional parameter default value."

Adding ? after a parameter name makes it "okay to omit." Writing paramName: type = initialValue instead sets a default value used whenever the caller doesn't pass one.

The example sets a default greeting with greet(name: string, greeting: string = "Hello"). The caller can either omit the greeting or specify one.

A common early mistake is confusing when to use an optional parameter (?) versus a default parameter. If you want a missing value to be treated as undefined, use ?; if you want a fallback value to be filled in automatically, use a default value โ€” that distinction is worth remembering.

In real projects, the more configuration options a function has, the more setting common values as defaults keeps the caller's code simple.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)