Mastering JSDoc: the complete guide for Javascript developers
Tags: javascript, programming, productivity, tutorial
Published: 2023-04-23 06:43:41

> Also available on my [blog](https://nikolasbarwicki.com/articles/mastering-jsdoc-the-complete-guide-for-javascript-developers)

## Introduction

As Javascript developers, we all understand the importance of writing clean, readable, and maintainable code. One of the ways we can achieve this is by documenting our code properly. That's where **JSDoc comes into play**.

[JSDoc](https://jsdoc.app/) is a **markup language** used to describe the structure and behavior of Javascript code. It provides a standard way of **documenting code** so that other developers can easily understand what each function, method, or class does, its input parameters, return values, and more.

JSDoc is especially **important in larger projects** with multiple developers or contributors, where maintaining a clear and concise documentation of the codebase is crucial. It helps avoid confusion, misunderstandings, and errors by making the code more transparent, consistent, and self-explanatory.

In this blog post, we'll cover the basics of JSDoc, its **benefits**, **best practice**, and **how to integrate** it with other tools. We'll also provide real-world examples to help you understand how to use JSDoc effectively in your projects.

## Basic Syntax of JSDoc

JSDoc is based on the **same syntax as regular Javascript comments**, with the addition of special tags and annotations to provide more structured documentation. Here's how to use JSDoc annotations to document your code.

To add JSDoc to a function, class, or method, simply add a comment block above the declaration, starting with the `/**` characters. Here's an example:

```javascript
/**
 * Calculates the sum of two numbers
 *
 * @param {number} a - The first number to add
 * @param {number} b - The second number to add
 * @returns {number} The sum of a and b
 */
function sum(a, b) {
  return a + b
}
```

In the above example, we've used the `@param` tag to describe the input parameters of the `sum()` function and the `@returns` tag to describe its return value.

Here's a brief overview of some commonly used JSDoc tags and their purpose:

- `@param`: describes a function or method's input parameters, including their data type, name, and description.
- `@returns`: describes the value returned by a function or method, including its data type and description.
- `@throws`: describes the error or exception thrown by a function or method, including its data type and description.
- `@deprecated`: indicates that a function or method is no longer recommended for use and provides an alternative if available.
- `@example`: provides an example of how to use a function or method.
  Here are some practical examples of JSDoc annotations and tags:

```javascript
/**
 * Calculates the area of a rectangle
 *
 * @param {number} width - The width of the rectangle
 * @param {number} height - The height of the rectangle
 * @returns {number} The area of the rectangle
 *
 * @example
 *
 * // returns 20
 * calculateRectangleArea(4, 5);
 */
function calculateRectangleArea(width, height) {
  return width * height
}
```

```javascript
/**
 * Searches for a given string in an array of strings
 *
 * @param {string} query - The string to search for
 * @param {string[]} strings - The array of strings to search in
 * @returns {boolean} True if the query is found in the array, false otherwise
 *
 * @example
 *
 * // returns true
 * searchInArray("foo", ["foo", "bar", "baz"]);
 */
function searchInArray(query, strings) {
  return strings.includes(query)
}
```

By using JSDoc annotations and tags like in the above examples, we can make our code more understandable and maintainable. In the next section, we'll discuss the benefits of using JSDoc in our projects.

## Benefits of Using JSDoc

There are **several benefits** to using JSDoc in your Javascript projects. Let's take a closer look at some of the key advantages:

### Improved Code Documentation and Clarity

One of the most significant benefits of JSDoc is that it makes code documentation **more consistent** and **easier to understand**. By using standardized annotations and tags, developers can provide clear and concise descriptions of what a function or method does, its input parameters, and expected output.

For example, consider this function that calculates the area of a circle:

```javascript
/**
 * Calculates the area of a circle.
 * @param {number} radius - The radius of the circle.
 * @returns {number} The area of the circle.
 */
function calculateCircleArea(radius) {
  return Math.PI * radius * radius
}
```

With JSDoc annotations, we can easily see that this function **takes a numeric radius parameter** and **returns a numeric value representing the area of the circle**. This information is especially helpful for team members who may not be familiar with the code or are new to the project.

### Easier Maintenance and Debugging

JSDoc can also make maintenance and debugging easier by **providing context for how code works**. By documenting the behavior and inputs of each function or method, developers can more easily identify bugs, errors, or inconsistencies in the codebase.

For example, consider this function that **converts a temperature** from Celsius to Fahrenheit:

```javascript
/**
 * Converts a temperature from Celsius to Fahrenheit.
 * @param {number} celsius - The temperature in Celsius.
 * @returns {number} The temperature in Fahrenheit.
 */
function celsiusToFahrenheit(celsius) {
  return (celsius * 9) / 5 + 32
}
```

### Better Understanding of Codebase

JSDoc can also help new developers or contributors better understand the codebase. By providing clear and concise documentation for each function, method, or class, developers can more easily navigate and understand the codebase.

For example, consider this class that represents a rectangle:

```javascript
/**
 * Represents a rectangle.
 * @class
 */
class Rectangle {
  /**
   * Creates a new rectangle.
   * @param {number} width - The width of the rectangle.
   * @param {number} height - The height of the rectangle.
   */
  constructor(width, height) {
    this.width = width
    this.height = height
  }

  /**
   * Calculates the area of the rectangle.
   * @returns {number} The area of the rectangle.
   */
  calculateArea() {
    return this.width * this.height
  }
}
```

With JSDoc annotations, we can easily see that this class represents a rectangle, has a constructor that **takes two numeric parameters for width and height**, and a method `calculateArea()` that returns the **area of the rectangle**. This information can be very helpful for new developers or contributors who are trying to understand the functionality of the codebase.

## Best Practices for Using JSDoc

JSDoc is a powerful tool that can help you document your Javascript code effectively, but to get the most out of it, it's important to **follow some best practices**. Here are some tips to help you use JSDoc efficiently in your projects:

### Consistency in JSDoc Style and Formatting

Consistency in style and formatting is essential for creating a clear and readable JSDoc documentation. It's important to establish a consistent style and format across your codebase to make it easier for other developers to read and understand your code.

Here's an example of a function with consistent JSDoc formatting:

```javascript
/**
 * Adds two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The sum of the two numbers.
 */
function add(a, b) {
  return a + b
}
```

### Keeping JSDoc Up-to-Date with Code Changes

It's important to keep your JSDoc annotations up-to-date with your code changes. Whenever you **modify a function or method**, make sure **to update** its corresponding JSDoc annotations.

Here's an example of a modified function and its updated JSDoc annotations:

```javascript
/**
 * Adds two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The sum of the two numbers.
 */
function add(a, b) {
  // Modified to handle negative numbers
  if (a < 0 || b < 0) {
    throw new Error('Cannot add negative numbers.')
  }
  return a + b
}
/**
 * Subtracts two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The difference of the two numbers.
 */
function subtract(a, b) {
  return a - b
}
```

### Utilizing JSDoc to Describe Complex Code Behavior and Logic

JSDoc can also be used to **describe complex code behavior** and logic that may not be immediately apparent from the code itself. This can help other developers understand how a function or method works and what it does under different conditions.

Here's an example of a complex function with JSDoc annotations:

```javascript
/**
 * Sorts an array of objects by a specified key.
 * @param {Object[]} arr - The array of objects to sort.
 * @param {string} key - The key to sort the objects by.
 * @param {string} [order='asc'] - The order to sort the objects in ('asc' or 'desc').
 * @returns {Object[]} The sorted array of objects.
*/
function sortByKey(arr, key, order = 'asc') {
// Sorts the array based on the specified key and order
arr.sort((a, b) => {
if (order === 'desc') {
return b[key] - a[key];
} else {
return
}
```

## Integrating JSDoc with Other Tools

JSDoc can be integrated with various tools to further improve your development workflow. Here are some examples:

### Editors and IDEs

Many modern editors and IDEs provide support for JSDoc, making it easier to write and maintain JSDoc annotations directly in your code. Let's take [Visual Studio Code](https://code.visualstudio.com/) as an example.

To get started with JSDoc in Visual Studio Code, install the [Document This extension](https://marketplace.visualstudio.com/items?itemName=oouo-diogo-perdigao.docthis), which automatically generates JSDoc annotations for your code based on the function signature.

```javascript
/**
 * A function that adds two numbers
 * @param {number} a - The first number
 * @param {number} b - The second number
 * @returns {number} The sum of a and b
 */
function add(a, b) {
  return a + b
}
```

### Documentation Generators

Finally, JSDoc can be used to generate documentation for your code using tools like JSDoc itself and [TypeDoc](https://typedoc.org/). These tools generate HTML or Markdown documentation based on your JSDoc annotations, making it easier for others to understand how your code works and how to use it.

Here's an example of how to use JSDoc to generate documentation for a function using the JSDoc CLI:

```javascript
/**
 * A function that divides two numbers
 * @param {number} a - The dividend
 * @param {number} b - The divisor
 * @returns {number} The quotient of a and b
 * @throws {Error} If b is zero
 */
function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero')
  }
  return a / b
}

/**
 * @module calculator
 */

module.exports = {
  divide,
}
```

You can then run the JSDoc CLI to generate documentation for the calculator module:

```bash
$ jsdoc calculator.js
```

This will generate HTML documentation in a `out/` directory, which you can open in your browser to view the documentation.

## Conclusion

In conclusion, JSDoc is an **essential tool** for Javascript developers who want to write clean, maintainable, and understandable code. By providing a standard way of documenting code, **JSDoc helps improve code quality**, productivity, and collaboration among team members.

By adopting JSDoc, you'll not only make your code more transparent and understandable for other developers, but you'll also improve your own coding skills by thinking more deeply about your code structure, behavior, and intent. So **let's make JSDoc a part of our coding best practices** and write better code together.