Optional and Default Parameters

Make parameters optional with ? or give them default values.

Syntaxfunction f(a: number, b = 10) { }

Add ? after a parameter name to make it optional β€” callers can leave it out. Inside the function its type includes undefined.

Alternatively, give a parameter a default value with =. If the caller omits it, the default is used instead.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A logging function makes the log level optional so callers can omit it when the default 'info' level is sufficient.
  • A utility function defaults a separator to ',' so callers only need to pass it when they want a custom delimiter.
  • A UI component rendering function makes a className parameter optional to avoid forced empty string arguments.

More examples

Optional parameter with ?

Marks level as optional (string | undefined) and applies a default with the nullish coalescing operator.

Example Β· ts
function log(message: string, level?: string): void {
  const lvl = level ?? 'info';
  console.log(`[${lvl.toUpperCase()}] ${message}`);
}

log('Server started');          // uses default
log('Disk full', 'error');      // uses provided level

Default parameter value

Uses a default parameter value so the separator is automatically string-typed and pre-filled when omitted.

Example Β· ts
function join(items: string[], separator: string = ', '): string {
  return items.join(separator);
}

console.log(join(['a', 'b', 'c']));         // 'a, b, c'
console.log(join(['a', 'b', 'c'], ' | ')); // 'a | b | c'

Optional and default combined

Combines a literal-union default parameter with an optional boolean, showing both patterns in one realistic signature.

Example Β· ts
function createButton(
  label: string,
  type: 'button' | 'submit' | 'reset' = 'button',
  disabled?: boolean
): string {
  const dis = disabled ? ' disabled' : '';
  return `<button type="${type}"${dis}>${label}</button>`;
}

Discussion

  • Be the first to comment on this lesson.
Optional and Default Parameters β€” TypeScript | SoundsCode