??), and how to express the same behavior with arrow functions.
Keywords: TypeScript functions, optional parameters, default parameters, nullish coalescing, arrow functions
First, define a simple Duck type and a daffy instance:
Basic function with an optional parameter
Here is a function that accepts aduck and an optional times argument. If times is not provided, the function defaults to 1 quack using nullish coalescing (??), which only treats null or undefined as “no value”.
Prefer
times ?? 1 over times || 1 when you want to treat only null or undefined as “no value” and still allow 0.Avoid using
times || 1 if 0 is a meaningful value for times — || treats 0 as falsy and will wrongly fall back to 1.Using a default parameter
You can also declare a default value directly in the parameter list. TypeScript infers the parameter type from the default, so an explicit: number is not required.
- With a default parameter (
times = 1), callers may omittimesand it will default to1. - If you explicitly want
timesto possibly beundefinedinside the function, use an optional parameter (times?: number) instead of a default.
Arrow function equivalent
You can write the same function as an arrow function. For most use cases arrow functions behave the same as regular function expressions, but be aware of differences inthis binding and hoisting.
Quick comparison
Summary
- Optional parameters are declared with
?(e.g.,times?: number) and may beundefined. - Default parameters are declared with
=(e.g.,times = 1) and supply an automatic fallback. - Prefer
??over||for fallbacks when0is a meaningful value. - Arrow functions provide a concise alternative; they differ from regular functions in
thisbehavior and hoisting.
- TypeScript function documentation: https://www.typescriptlang.org/docs/handbook/functions.html
- MDN: Nullish coalescing operator (
??): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator