How to

How to Document JavaScript Code Using JSDoc

Proper code documentation is an important yet often overlooked aspect of software development. As a developer, you’ll be used to writing clean, efficient code, but you may be less experienced at writing good documentation.


Good documentation is useful for anyone working with your code, whether it’s other members of your team, or you, yourself, at a later date. It can explain why you’ve implemented something a particular way or how to use a particular function or API.

For JavaScript developers, JSDoc is a good way to start documenting your code.


What Is JSDoc?

Documenting code can be complex and tedious. However, more people are recognizing the benefits of a “docs as code” approach, and many languages have libraries that help automate the process. For simple, clear, and concise documentation. Just like the Go language has GoDoc to automate documentation from code, so JavaScript has JSDoc.

JSDoc generates documentation by interpreting special comments in your JavaScript source code, processing these comments, and producing bespoke documentation. It then makes this documentation available in an accessible HTML format.

This keeps the documentation within the code, so when you update your code, it’s easy to update the documentation.

Setting Up JSDoc

The creators of JSDoc have made it easy to get started and set up JSDoc in your JavaScript project.

To install JSDoc locally, run:

 npm install --save-dev jsdoc

This will install the library in your project as a dev dependency.

To use JSDoc, you will use special syntax comments inside your source code. You will write all your documentation comments within /** and */ markers. Inside these, you can describe defined variables, functions, function parameters, and a lot else.

For example:

 
 * Gets User by name.
 * @param {string} name - The name of the User
 * @returns {string} User
 */

function getUser(name) {
  const User = name;
  return User;
}

The @param and @returns tags are two of the many special keywords that JSDoc supports to explain your code.

To generate the documentation for this code, run npx jsdoc followed by the path to your JavaScript file.

For example:

 npx jsdoc src/main.js

If you installed JSDoc globally, you can omit the npx flag and run:

This command will generate an out folder in your project root. Inside the folder, you will find HTML files representing the pages of your documentation.

You can view the documentation by setting up a local web server to host it, or simply by opening the out/index.html file inside a browser. Here’s an example of what a documentation page will look like by default:

A screenshot of jsdoc document

Configuring the JSDoc Output

You can create a configuration file to change JSDoc’s default behavior.

To do so, create a conf.js file and export a JavaScript module inside this file.

For example:

 module.exports = {
  source: {
    includePattern: ".+\\.js(doc|x)?$",
    excludePattern: ["node_modules"],
  },
  recurseDepth: 5,
  sourceType: "module",
  opts: {
    template: "path/to/template",
    destination: "./docs/",
    recurse: true,
  },
};

Inside the configuration file are various JSDoc configuration options. The template option lets you use a template to customize the documentation’s appearance. JSDoc’s community provides many templates that you can use. The package also allows you to create your own personalized templates.

To change the location of the generated documentation, set the destination config option to a directory. The example above specifies a docs folder in the project’s root.

Use this command to run JSDoc with a configuration file:

 jsdoc -c /path/to/conf.js

To make it easier to run this command, add it as a scripts entry inside your package.json file:

 "scripts": {
    "dev": "nodemon app.js",
    "run-docs": "jsdoc -c /path/to/conf.js"
 },

You can now run the npm script command inside a terminal.

An Example of Documentation Generated With JSDoc

Below is a simple arithmetic library with add and subtract methods.

This is an example of well-documented JavaScript code:

 
 * A library for performing basic arithmetic operations.
 * @module arithmetic
 */
module.exports = {
    
     * Adds two numbers.
     * @param {number} a - The first number.
     * @param {number} b - The second number.
     * @return {number} The sum of the two numbers.
     * @throws {TypeError} If any of the arguments is not a number.
     *
     * @example
     * const arithmetic = require('arithmetic');
     * const sum = arithmetic.add(5, 10);
     * console.log(sum);
     */
    add: function(a, b) {
        if (typeof a !== 'number' || typeof b !== 'number') {
            throw new TypeError('Both arguments must be numbers.');
        }

        return a + b;
    },

    
     * Subtracts the second number from the first number.
     * @param {number} a - The number to subtract from.
     * @param {number} b - The number to subtract.
     * @return {number} The result of the subtraction.
     * @throws {TypeError} If any of the arguments is not a number.
     *
     * @example
     * const arithmetic = require('arithmetic');
     * const difference = arithmetic.subtract(10, 5);
     * console.log(difference);
     */
    subtract: function(a, b) {
        if (typeof a !== 'number' || typeof b !== 'number') {
            throw new TypeError('Both arguments must be numbers.');
        }

        return a - b;
    }

    
};

The JSDoc comments provide a clear and comprehensive description of the library and its methods, including:

  • A description of the library and its purpose.
  • Each method’s parameters, including their type and a brief description.
  • The value and type that each method returns.
  • The errors that each method can throw and the conditions that cause it.
  • An example of how to use each method.

The comments also include the @module tag to indicate that this file is a module and the @example tag to provide a code example for each method.

Documenting Developer Code the Right Way

As you can see, JSDoc is a very useful tool to get you started documenting JavaScript code. With its easy integration, you can generate quick and detailed documentation as you write your code. You can also maintain and update the documentation right in your workspace.

However, as useful as JSDoc’s automation is, you should still adhere to certain guidelines so you can create quality documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *