Course contentsShow
← JavaScript
Lesson 2615 of 2,72353. Type Safety Without TypeScriptFree lesson

Union Types and Optional Parameters

Express multiple possible types with the pipe operator and mark parameters as optional in JSDoc.

Union Types and Optional Parameters

You'll learn how to document functions that accept multiple data types and parameters that may be omitted using JSDoc syntax.

The Core Idea

Sometimes a parameter can legitimately accept different types—maybe a function takes either a string ID or a numeric ID. Other times, a parameter is completely optional. JSDoc gives you clean syntax for both scenarios without needing TypeScript.

Union types use the pipe operator (|) to list alternatives:

/**
 * @param {string|number} id - User identifier
 */
function findUser(id) {
  // id can be "abc123" or 42
}

This tells readers (and tools) that id might be a string or a number—both are valid.

Optional parameters wrap the type in square brackets or use explicit syntax:

/**
 * @param {string} name
 * @param {number} [age] - Optional age
 */
function greetUser(name, age) {
  if (age !== undefined) {
    console.log(`${name} is ${age} years old`);
  } else {
    console.log(`Hello, ${name}`);
  }
}

You can also write @param {number|undefined} age to be explicit that age might be undefined.

Combining Both

You can mix unions and optionality:

/**
 * @param {string|number} id
 * @param {boolean} [verify] - Whether to verify existence
 */
function deleteRecord(id, verify) {
  // id is required but flexible; verify is optional
}

Think of union types as "either/or" choices and optional parameters as "you can skip this." Both make your function contracts more honest without forcing callers into rigid types.

Key Takeaway: Use | in JSDoc to allow multiple types for a parameter, and wrap parameter names in [brackets] or allow undefined in the union to mark them as optional—giving you flexible, self-documenting JavaScript.