loading...
Cover image for Document your Javascript code with JSDoc

JSDoc Document your Javascript code with JSDoc

paulasantamaria profile image Paula Santamaría ・5 min read

Introduction

In this post I'll try to cover everything you need to know to get started with JSDoc. I'll also share with you some other cool stuff I learned about it that you might find useful.

Table of contents


JSDoc is an open source API documentation generator for Javascript. It allows developers to document their code through comments. Here's an example:

/**
 *  Retrieves a single file by id.
 *  @param {string} id File identifier.
 *  @returns {File} File object.
 */
const getFileById = (id) => {
    // ...
}

Once your code is fully documented you can easily generate a website containing all the API documentation by running a simple command. How cool is that?

Here's how the previous code would look like in the generated website:

A screenshot of the documentation formatted in the website including all the JSDoc tags specified in the previous code

Installation

Install JSDoc globally through npm using this command:

npm install -g jsdoc

Or use the following command to install it for a single project:

npm install --save-dev jsdoc

More info on installation here

Now, to be honest, even though I've been using JSDoc comments to document my code for a long time, I didn't install this package until a few weeks ago because I didn't actually needed to generate the website. Instead I was just using it with VSCode, but I'll talk about that later in this post.

Usage

Document

To start documenting your code all you have to do is add a comment starting with /** over each block of code you want to document: Modules, methods, classes, functions, etc.

You can keep it simple by just adding a description:

/**
 * Retrieves a user by email.
 */
const getByEmail = async (email) => {
    // ...
}

Or you can take full advantage of JSDoc using tags:

/**
 * Retrieves a user by email.
 * @async
 * @method
 * @param {String} email - User email
 * @returns {User} User object
 * @throws {NotFoundError} When the user is not found.
 */
const getByEmail = async (email) => {
    // ...
}

There's a huge list of tags you can choose from to document your code as thoroughly as you as please.

Remember, the more info you add to your comments, the more detailed your API documentation will be. But also, find the amount of detail that feels right to you. It's better to have all your code documented with only a few tags than to have only a few methods fully documented using all the tags because it was too much and you couldn't keep up.

Export

After adding the comments all that's left to do is generate your documentation website:

Export files or folders

Simply call jsdoc and add the path to the file or folder.

jsdoc path/to/my/file.js

To include many files or folders, add all their paths separated by a single space.

Export all files recursively

jsdoc -r .

Use a configuration file

It's likely that you're working on a big project with many files and folders that you want to export, and also some that you need to exclude (I'm looking at you, node_modules). If that's the case you may want to use a JSDoc Configuration file.

Using a configuration file allows us to customize JSDoc behavior, like:

  • Which folders or files should be included and which excluded.
  • How deep JSDoc will go when we use the --recurse option.
  • Apply customizations to the template
  • etc

All you need to do is create a .json file containing the settings you want and then use the -c or --configure option to tell JSDoc to where they are:

jsdoc -c /path/to/conf.json

Here's a (very simple) example that I often use:

{
    "source": {
        "includePattern": ".+\\.js(doc|x)?$",   // Only process file ending in .js, .jsdoc or .jsx
        "include": ["."],                       // Check all folders.
        "exclude": ["node_modules"]             // Be gone, node_modules.
    },
    "recurseDepth": 10,                         // Only go 10 levels deep.
    "opts": {
        "destination": "./docs/",               // Where I want my docs to be generated.
        "recurse": true                         // Same as using -r or --recurse
    }
}

Pro tip:
You may want to add the command to your package.json scripts:

"scripts": {
    "generate-docs": "jsdoc -c /path/to/my/conf.js"
}

Then simply use npm run generate-docs from the command-line.

Or you can use sillier names for the script, like: docs-pls, gimme-docs or ill-have-the-large-docs-with-extra-docs (well, maybe not the last one 😅 ).

More info on Configuration here

Other cool stuff about JSDoc

Built in support in VSCode

So, like I said, I was enjoying JSDoc even before installing it, and that's because VSCode has built-in support for JSDoc annotations, which includes:

  • A snippet that builds the JSDoc annotation structure for you when you type /** (and then press enter) before a function declaration. VSCode automatically generates the structure of the JSCode annotations for a function
  • Rich hover information VSCode displays all the tags from a function when you hover said function
  • Info about the function signature as you're using it VSCode displays info about the function params when the user types the name of the function

For more info about JSDoc support in VSCode check VSCode docs.

Use a custom layout

You can create your own template for your API documentation by generating a custom layout.tmpl file and setting the option templates.default.layoutFile to the path of your custom layout in your JSDoc configuration file.

Don't have the time to generate your own template? Here are a few pretty neat template projects you can use:

JSDoc and Swagger

This project swagger-jsdoc integrates JSDoc with swagger allowing you to write the specification for your routes using the tag @swagger over your block code:

  /**
   * @swagger
   * /:
   *   get:
   *     description: Returns all users.
   *     responses:
   *       200:
   *         description: All users were returned.
   */
  app.get('/users', (req, res) => {
    // ...
  });

Know any other interesting JSDoc feature?

Tell me in the comments! 👇

Posted on by:

paulasantamaria profile

Paula Santamaría

@paulasantamaria

Passionate about creating stuff. Gamer, digital artist and guitarist on my free time.

Discussion

markdown guide
 

That swagger jsdoc integration seems interesting - I'm in the process of updating swagger doc file and it is rather inconvenient to do it "by hand" by checking the code every time.

Thanks for info on vs code, I'm trying to get off webstorm and that seems like a decent alternative.

 

Thanks for reading!
I loved the swagger integration too. It’s better than having to write the whole definition manually in separate files. But, to be honest, it’s still pretty tedious... So I'm still looking for better solutions. This one seems interesting too, but I haven't tried it yet.
I've been a huge fan of VSCode for years, its light and minimalist, but also highly customizable. You should definitely try it!

 
 

Hi Paula ... nice intro to JSDoc!

You may be interested in this article (bit.ly/docJS) that describes how you can integrate a User's Guide (via GitBook) with your low-level API (using JSDoc).

You can see this in action in the docs of one of my open-source projects: feature-u.js.org/

 

Thank you Kevin! I've never tried GitBook, but sounds interesting. I'll definitely check out your article, looks like a great way to get the best of both worlds combined!

 

Markdown is supported in this style of comment I believe

 

You're absolutely right, thank you! I haven try it yet, but for anyone interested, here's the official doc about how to use markdown in JSDoc. Seems pretty straight forward.

 

Youre welcome, this is how to take your js doc comments to the next level. 😅

There is no config for vscode btw it just works.

 

You can even make TypeScript type check your JS files based on JSDoc comments: typescriptlang.org/docs/handbook/t...

 
 

Thanks. documentation.js is a very convenient complement to JSDoc.

 
 

Thanks for this - have wanted to get into inline documentation, but had not seen a nice intro (and the official docs are a bit... Dry).

 

I'm flattered :D once you start using JSDoc you won't be able to stop, trust me.

 
 

JSDoc is life. Today I realized I never used it by installing it on projects I worked on 😅 just followed the syntax and tags

 

So I'm not the only one who did that, awesome! 🤣

 

This is great, thank you! We use jsdocs at work, so this was a great article on how we can use it better.

 

Glad I could help! JSDoc has been really useful, even when I'm working alone, it helps me realize if a function or method should be improved or refactored.

 

As a QA engineer and frontend on my free time this is useful for both worlds 👍🏼

 
 

Thank you for sharing this information, I already replicated in my node projects.