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

Function Types and Callbacks

Document callback parameters and function types using JSDoc's function signature syntax.

Function Types and Callbacks

You'll learn how to document functions that accept other functions as parameters using JSDoc's function signature syntax.

Why Document Callbacks?

When a function takes another function as an argument (a callback), you need to tell developers what that callback should look like: what parameters it receives, what it should return, and whether those parameters are optional. JSDoc provides special syntax to describe these function shapes inline.

The Basic Function Signature Syntax

For simple callbacks, use @param {function(paramType): returnType}:

/**
 * @param {function(number): boolean} predicate - Tests each element
 * @param {number[]} numbers
 * @returns {number[]}
 */
function filterNumbers(predicate, numbers) {
  return numbers.filter(predicate);
}

This tells readers: "predicate is a function that takes a number and returns a boolean."

Multiple Parameters and Complex Callbacks

For callbacks with multiple parameters, separate them with commas:

/**
 * @param {function(string, number): void} callback
 * @param {string[]} items
 */
function forEachWithIndex(callback, items) {
  items.forEach((item, index) => callback(item, index));
}

Combining with @typedef for Reusability

For complex callback types used in multiple places, define them once with @typedef:

/**
 * @typedef {function(Error|null, string): void} NodeCallback
 */

/**
 * @param {NodeCallback} callback
 */
function readFileAsync(callback) {
  // Implementation
}

This makes your documentation clearer and avoids repeating complex function signatures.

Key Takeaway: Use function(paramTypes): returnType syntax within @param tags to document what shape callbacks must have, making function contracts explicit even without TypeScript.