Skip to main content
In this lesson we’ll explore TypeScript functions by helping Elmo make his ducks quack. You’ll learn how to declare parameters (optional vs default), when to use nullish coalescing (??), 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 a duck 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”.
Console output:
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.
Console output:
Notes:
  • With a default parameter (times = 1), callers may omit times and it will default to 1.
  • If you explicitly want times to possibly be undefined inside 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 in this binding and hoisting.

Quick comparison

Summary

  • Optional parameters are declared with ? (e.g., times?: number) and may be undefined.
  • Default parameters are declared with = (e.g., times = 1) and supply an automatic fallback.
  • Prefer ?? over || for fallbacks when 0 is a meaningful value.
  • Arrow functions provide a concise alternative; they differ from regular functions in this behavior and hoisting.
Further reading:

Watch Video