Modern JavaScript Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it…

The main idea for JSDoc is to document your APIs, including functions, classes, methods, and whatnot. JSDoc comments are expected to precede the code that is being documented. Comments start with /** and end with */; the double star distinguishes them from normal comments.

Don't go overboard with stars, because if you write three or more, then the comment will also be ignored; JSDoc expects two stars, no more, no less.

The following code block shows the simplest possible example, how you might document a function by providing a description of its goals and arguments:

/**
* Solves the Hanoi Towers puzzle, for any number of disks.
*
* @param {number} disks - How many disks to move
* @param {string} from - The starting pole's name
* @param {string} to - The destination pole's name
* @param {string} extra - The other pole's name
*/
const hanoi = (disks, from, to, extra) => {
if (disks === 1) {
console.log(`Move disk 1 from post ${from} to post ${to}`);
} else {
hanoi(disks - 1, from, extra, to);
console.log(`Move disk ${disks} from post ${from} to post ${to}`);
hanoi(disks - 1, extra, to, from);
}
};

The @param notation is a block tag, which introduces a code item, in this case, a parameter of the function. A (partial) list of common tags is as follows:

 

There are more tags, such as @private, to identify a member as private, but since JS doesn't really provide that feature, I skipped it. Other tags are more specific, and you may not use them, such as @generator or @mixin. If you want to see the complete list of possible block (and also a couple of inline) tags, checkout http://usejsdoc.org/index.html.

A confession: we won't be using JsDoc very much in this book, but only because all the needed explanations will be given in the text itself. For normal work, I'd always use it, but in this book it would mainly be redundant.