JSDoc Cheat Sheet

JSDoc is a markup language used to annotate JavaScript code for generating documentation. It is commonly used with tools like ESDoc or JSDoc itself to generate documentation. Below is a cheat sheet for writing JSDoc comments:

Basic Usage

/**
 * This is a JSDoc comment for a function.
 * @param {Type} paramName - Description of the parameter.
 * @return {Type} Description of the return value.
 */
function myFunction(paramName) {
  // function body
}

Data Types

Basic Types:

  • string, number, boolean, Object, Array, Function, null, undefined, etc.

Custom Types:

  • Use @typedef to create custom types.
/**
 * @typedef {Object} CustomType
 * @property {string} prop1 - Description for prop1.
 * @property {number} prop2 - Description for prop2.
 */

Function Parameters

Required Parameter:

/**
 * @param {Type} paramName - Description for paramName.
 */

Optional Parameter:

/**
 * @param {Type} [paramName] - Description for paramName.
 */

Default Value:

/**
 * @param {Type} [paramName=default] - Description for paramName.
 */

Return Type

/**
 * @return {Type} Description for the return value.
 */

Function Description

/**
 * Description for the function.
 * @param {Type} paramName - Description for paramName.
 * @return {Type} Description for the return value.
 */
function myFunction(paramName) {
  // function body
}

Class Description

/**
 * Description for the class.
 * @class
 */
class MyClass {
  // class body
}

Class Property

/**
 * @class
 * @classdesc Class description.
 * @property {Type} propertyName - Description for propertyName.
 */
class MyClass {
  // class body
}

Class Method

/**
 * @class
 * @classdesc Class description.
 */
class MyClass {
  /**
   * Description for the method.
   * @param {Type} paramName - Description for paramName.
   * @return {Type} Description for the return value.
   */
  myMethod(paramName) {
    // method body
  }
}

Events

/**
 * Triggered when something happens.
 * @event MyEvent
 * @type {Object}
 * @property {string} eventProperty - Description for eventProperty.
 */

Callback Function

/**
 * Callback function to be executed.
 * @callback MyCallback
 * @param {Type} param1 - Description for param1.
 * @param {Type} param2 - Description for param2.
 * @return {Type} Description for the return value.
 */

Module Definition

/**
 * @module myModule
 */

Important Notes

  • Use @param, @return, and @typedef to provide additional information about the code.
  • Use @example to include examples in the documentation.
  • JSDoc supports a variety of tags for different purposes; refer to the official JSDoc documentation for more details.
  • Some IDEs and text editors provide support for JSDoc, allowing you to generate documentation comments automatically.

JSDoc is a powerful tool for documenting your JavaScript code, making it easier for others to understand and use your functions, classes, and modules.