Documentation in Javascript

Notes

It is invariably useful and important to provide documentation for your code, but in a way that is usable by the application’s users. This is typically done by specifying certain comments in code that are automatically processed to produce a documentation webpage.

There are fundamentally a couple of different kinds of documentation:

There are at least two very different approaches to automatic code documentation:

We will be seeing documentationjs in this section, but other systems are similar.

In any case, most of these systems allow you to customize the CSS for your pages, and most allow you to use Markdown syntax in your comments.

JSDoc comments

JSDoc comments are special comments that are processed by JSDoc and other systems:

Here is an example of the documentation for the TaskAppController’s constructor:

/**
 * Create a new `TaskListController`.
 *
 * @param {TaskList} taskList     The `TaskList` instance to manage.
 * @param {jQuery}   domEl        The DOM Element to use for printing the list.
 * @returns {TaskListController} A new `TaskListController` instance.
 * @example TaskListController.new(myList, $('#list'));
 * @memberof TaskListController
 * @static
 * @public
 */

This creates a classification of sorts for our comments, into 3 types:

/**
 * "slash-star-star" comments are meant to be processed by automatic tools.
 * These tools might generate documentation, or look for linting instructions.
 */
/*
 * "slash-star" comments are used for large comments that describe some
 * feature of a file but that are not meant to be automatically processed.
 */
// Inline comments are meant for clarifying code snippets, for developers
// working on the code.

JSDoc tags

You can find what all the available tags are in JSDoc’s documentation. But some standard ones are:

@param
an input given to the function as a parameter, along with its expected type.
@returns
what the output value of the function is.
@name
explicitly set the documented name of the item, if the automatically detected name is not suitable.
@private
document code bo do not include it in the generated documentation. There’s also @public and @protected. You can choose to generate some of this
@example
inline code examples
@static, @instance
indicate if it is a static/class-level function or variable an instance/prototype-level function or variable.
@kind
indicate what kind of an item it is (function etc). Can also use more direct tags instead, like @module, @class, @method etc
@event
can be used for documenting events.

Running the documentation

You can generate various “results” from this documentation. That all depends on the program you use. For instance with documentationjs you can:

The simplest thing to do would be something like this:

documentation build js/taskListController.js -f html -o docs
# This will open the file
documentation build --watch js/taskListController.js -f html -o docs