# Documenting JavaScript With YUIDoc

Documenting your code is somewhat like testing; we all know we should do it, we’re not really sure how, and most folks, if we're honest, simply don’t, but those who do are huge proponents of it. This tutorial will get you up to speed on one of the best ways to tackle it: YUIDoc.

## What is YUIDoc?

YUIDoc will generate API documentation based on comments that you write.

YUIDoc is a NodeJS app that will generate API documentation (in the form of HTML), based on comments that you write in your JavaScript source code. Actually, it's not just for JavaScript: any programming language that supports block comments delimited by /* */ works for YUIDoc. As you might guess, YUIDoc is one of the tools that Yahoo! publishes along with their YUI Library.

To install YUIDoc, you’ll need NodeJS and the Node package manager (npm) installed first. Then, you can install YUIDoc via npm -g install yuidocjs. You’ll use it by running yuidoc <path to js folder>; more on this later.

## It's All About the Tags

So, you know that YUIDoc gets its documentation from the multiline comments in the source file. Of course, you might have comments that aren’t part of the documentation. For YUIDoc to recognize a comment as significant, it must start with a double start: /**. So:

 1 /**  2 YUIDoc will process this  3 */  4 5 /*  6 But not this  7 */ 

Of course, it's what’s inside that counts (inside the comment blocks, that is). Each must include one and only one primary tag; it can also include zero or more secondary tags. Really, YUIDoc is that simple: add comments with the right tags to your code, and presto: documentation! So let’s learn some tags. Here’s how we’re going to do this: we’ll go over the tags, and where they are used, with simple examples of their usages; then, we’ll write and document some code so you have a better idea of how the tags work together.

## Primary Tags

Before getting into the primary tags, remember that each comment block can only have a single primary tag. These describe what a given chunk of code is.

### @module

The @module tag describes a group of relate classes. (Yes, yes, JavaScript doesn’t have classes: YUIDoc is referring to constructor functions.) If you were using YUIDoc to document BackboneJS, the Backbone object would be a module, because it holds the Model, Collection, View, and other classes. Right after the tag, you put the name of the module.

 1 /**  2 @module Backbone  3  */  4  var Backbone = Backbone || {}; 

### @class

The @class tag aptly describes a single class. In the YUI Library, this usually means a constructor function, but if you prefer to use a different pattern and call that your class, you can do that, too. Every comment with a @class tag should also have a @static or @constructor tag (secondary tags which we’ll discuss shortly).

 1 /**  2 @class Model  3  */  4  function Model () {} 

If your class is part of a module, you don’t have to do anything within the @class comment to designate that: just make sure that there’s an @module comment block at the top of that file.

### @method

Of course, every class will have at least a few methods, and you’ll use the @method tag to describe them. The method name will go after the tag, and you’ll use the secondary tags @return and @params to describe the method.

 1 /**  2 @method render  3 */  4 View.prototype.render = function (data) {} 

### @property

The @property tag is used to tag the properties of a class. You’ll want to use the @type and @default secondary tags with this one, for sure.

 1 /**  2 @property templateString  3 */  4 this.templateString = "div"; 

### @event

If you have special custom events that a class can fire, you’ll want to use the @event tag to describe them. Here’s what the YUIDoc documentation has to say:

An @event block is somewhat similar to a @method block, except that @return is irrelevant, and @param is used to describe properties hanging off the event object that callbacks listening for the event receive.

## Secondary Tags

Comment blocks can have more than one secondary tag; they’ll often have a handful, and sometimes even more than one of the same type. Let’s look at some of the ones you’ll use often.

### @submodule

If you’re dividing your modules into submodules (maybe a submodule per file, maybe not), the @submodule tag is at your service.

 1 /**  2 @module Util  3 @submodule array  4 */  5 Util.array = {}; 

### @extends

The @extends tag is useful when you have superclass/subclass relationships. You can claim what class is the parent of the currently documented class:

 1 /**  2 @class AppView  3 @extends Backbone.View  4 */  5 var AppView = Backbone.View.extend({}); 

### @constructor

If a class can be instantiated, that means it needs a constructor function. If you’re using the standard prototypal pattern in JavaScript, the class declaration is also the constructor. That means you’ll often see something like this:

 1 /**  2 @class Recipe  3 @constructor  4 */  5 function Recipe () {} 

In fact, you probably recall me saying that every @class tag should have either a @constructor or @static secondary tag.

### @static

Speaking of @static, here it is. A class is considered static when you cannot create an instance of it. A good example of this is the built-in Math object: you never create an instance of it (new Math()), you call its methods from the class itself.

 1 /**  2 @class MathHelpers  3 @static  4 */  5 var MathHelpers = {}; 

A method can also be static: if a class can be instantiated, but also has some class-level methods, these methods are considered static (they’re called on the class, not the instance).

 1 /**  2 @class Person  3 @constructor  4 */  5 function Person () {}  6 7 /**  8 @method all  9 @static  10 */  11 Person.all = function () {}; 

In this example, you can create a Person instance, but the all method is static.

### @final

This tag is used for properties or attributes, and marks said property as a constant: it should not be changed. While JavaScript doesn’t have real constants in its current state, your coding pattern or style guide might use them in principle, so this will be useful for that.

 1 /**  2 @property DATE_FORMAT  3 @final  4 */  5 var DATE_FORMAT = "%B %d, %Y"; 

### @param

Here’s an important one: the @param tag is used to define the parameters of a @method (including a @constructor) or an @event. There are three bits of info that go after the @param tag: the name of the parameter, the type (which is optional), and the description. These can either be in the order name type description or type name description; but in either case, the type must be surrounded by curly braces.

 1 /**  2 @method greet  3 @param person {string} The name of the person to greet  4 */  5 function greet (person) {} 

There are a few ways to customize the name part as well. Putting it in square brackets marks it as optional, while putting =someVal after it shows what the default value is (obviously, only optional parameters have a default value). Then, if it is a placeholder for more than one argument, append * to show that. (Obviously, name* is a placeholder for 1 or more arguments, while [name]* is a placeholder for 0 or more).

 1 /**  2 @class Template  3 @constructor  4 @param template {String} The template string  5 @param [data={}] {Object} The object whose properties will be rendered in the template  6 */  7 function Template (template, data) {} 

### @return

Most of your methods will want to return a value, so this is the tag that describes that value. Don’t forget to tell it what type the value is, and give it a description.

 1 /**  2 @method toHTML  3 @param [template=Recipe.defaultTemplate] {Template} A template object  4 @return {String} The recipe contents formatted in HTML with the default or passed-in template.  5 */  6 Recipe.prototype.toHTML = function (template) {  7  return "whatever";  8 }; 

### @type

Remember the @property primary tag? You’ll want to define what type those properties are, right? Well, the @type tag is just what you need. Specify the type after the tag; you can also offer multiple types by separating them with vertical bars:

 1 /**  2 @property URL  3 @type String  4 */  5 URL: "https://code.tutsplus.com",  6 7 /**  8 @property person  9 @type String|Person|Object  10 */  11 this.person = new Person(); 

### @private / @protected

Traditional programming languages offer private properties or methods: these aren’t accessible from outside of the instance. Just like constants, JavaScript has them by practice only, but you can use @private to tag these if you use them. Note that YUIDoc doesn’t show private properties in the docs it generates (that makes sense), so this allows you to document a feature for your own benefit and not have it show up in the docs.

 1 /**  2 @method _toString  3 @private  4 */  5 var _toString = Object.prototype.toString.call; 

Protected properties and methods are half-way between public and private: they’re only accessible from within instances and instances of subclasses. If that’s a thing you do in JavaScript, here’s your tag: @protected.

### @requires

If a module depends on one or more other modules, you can use @requires to mark that:

 1 /**  2 @module MyFramework.localstorage  3 @requires MyFramework  4 */ 

Note that @requires could also take a list of dependancies, separated by commas.

### @default

When declaring a @property, you might find it useful to give it a @default value. @default should always be used with @type.

 1 /**  2 @property element  3 @type String  4 @default "div"  5 */  6 element: "div", 

### @uses

Like we’ve said, JavaScript doesn’t really have classes, but it's flexible enough to create the illusion of classes, and even sub-classes. What’s even more cool is that it's flexible enough to have mixins or modules: this is where one class “borrows” properties or methods from another class. And it's not inheritance either, because you can mix in parts of more than one class (Of course, YUI has the ability to do this, but so do Dojo and other libraries). If you’re doing this, you’ll find @uses very useful: it lets you declare what classes a given class is mixing in parts of.

 1 /**  2 @class ModalWindow  3 @uses Window  4 @uses DragDroppable  5 */  6 var ModalWindow = new Class({  7  mixes: [Window, DragDroppable],  8  ...  9 }); 

Note: I just made up that mixin syntax, but I’m pretty sure I’ve seen something similar somewhere.

### @example

Want to include an example of how to use a particular piece of code? Use the @example tag, and then write the example below, indenting it one level. You can add as many examples as you’d like.

 1 /**  2 @method greet  3 @example  4  person.greet("Jane");  5 */  6 Person.prototype.greet = function (name) {}; 

### @chainable

You’re probably familiar with chainable methods from jQuery. You know, where you can call a method off a method call, because the methods return the object? Mark your methods as such with @chainable.

 1 /**  2 @method addClass  3 @chainable  4 */  5 jQuery.prototype.addClass = function (class) {  6  // stuff;  7  return this;  8 } 

### @deprecated / @since / @beta

These three tags are all about support for the code (and it could be any code: module, class, method, or something else). Use @deprecated to mark some functionality as no longer the best way to do it (deprecated functionality will probably be removed in a future version of the code). Optionally, you can include a message that explains what the current way to do it is.

 1 /**  2 @method toJSON  3 @deprecated Pass the object to JSON.parse instead  4 */  5 Something.toJSON = function () {}; 

The @since tag just tells readers what version the given code what added in. And @beta marks beta code: YUI suggests that @beta code might “undergo backwards-incompatible changes in the near future.”

 1 /**  2 @class Tooltip  3 @since 1.2.3  4 @constructor  5 */  6 function Tooltip () {} 

### @extension / @extensionfor / extension_for

The @extension tag (and its aliases) is pretty much the opposite of @uses. Use it to mark which classes the extension class can be mixed into. Of course, realize that this doesn’t mean it's always mixed in, just that it can be.

 1 /**  2 @class Draggable  3 @extensionfor ModalWindow  4 */ 

Before we look at an actual example, let me point out two more things about the documentation comment blocks.

First, you’ll often want to add a bit more information about your code than what the tags offer. Maybe you want to describe the purpose of the methods, or how a class fits into the bigger picture. Add these comments at the top of the comment block, above any of the tags. YUIDoc will notice them and include them in the documentation.

 1 /**  2 The Router class is used for . . .  3 @class Router  4 @static  5 */  6 var Router = {}; 

Second, you’ll be pleased to know that these comments, as well as any descriptions or message written after the tags, can be written in Markdown, and YUIDoc will convert it to the correct HTML. You can even indent example code blocks in your comments and get syntax highlighting!

## An Example

Now that you’ve learned the tags, let’s actually write some code and document it. Let’s create a Store module, which holds two classes: Item and Cart. Each Item instance will be a type of item in the store inventory: it will have a name, a price, and a quantity. A Cart instance can add items to the cart and calculate the total price of the items in the cart (tax included). It's fairly simple, but gives us enough varied functionality to use many of the tags we’ve discussed. I’ve put all the following code in store.js.

We start by creating the module:

 1 /**  2 * This module contains classes for running a store.  3 * @module Store  4 */  5 6 var Store = Store || {}; 

Now, let’s create a “constant”: the tax rate.

 1 /**  2 * TAX_RATE is stored as a percentage. Value is 13.  3  * @property TAX_RATE  4  * @static  5  * @final  6  * @type Number  7 */  8 9 Store.TAX_RATE = 13; 

This is a constant (@final) @property of @type Number. Notice I’ve included @static: this is because, for some reason, when we generate the documentation for this file, YUIDoc will display this as a property of our Item class: it seems that YUIDoc doesn’t support having a property on a module. I guess I could create a static class to hold this constant (and other constants that might come if we further developed this), but I’ve left it this way for a reminder: to use a tool like YUIDoc to its fullest potential, you might have to change the way you code. You’ll have to decide if that’s what you want to do.

Now, for the Item class:

 1 /**  2  * @class Item  3  * @constructor  4  * @param name {String} Item name  5  * @param price {Number} Item price  6  * @param quantity {Number} Item quantity (the number available to buy)  7  */  8 9 Store.Item = function (name, price, quantity) {  10  /**  11  * @property name  12  * @type String  13  */  14  this.name = name;  15  /**  16  * @property price  17  * @type String  18  */  19  this.price = price * 100;  20  /**  21  * @property quantity  22  * @type Number  23  */  24  this.quantity = quantity;  25  /**  26  * @property id  27  * @type Number  28  */  29  this.id = Store.Item._id++;  30  Store.Item.list[this.id] = this;  31 }; 

As you can see, this constructor has three parameters. Then, there are three properties inside the constructor that we’re also describing. Since we want to give every Item a unique ID, we need to store a static (class-level) property to increment the ID, and another static property, an object that tracks the Items by their ID.

 1 /**  2  * _id is incremented when a new item is created, so every item has a unique ID  3  * @property id  4  * @type Number  5  * @static  6  * @private  7  */  8 Store.Item._id = 1;  9 10 /**  11  * @property list  12  * @static  13  * @type Object  14  */  15 Store.Item.list = {}; 

How about the Cart class?

 1 /**  2  * @class Cart  3  * @constructor  4  * @param name {String} Customer name  5  */  6 7 Store.Cart = function (name) {  8  /**  9  * @property name  10  * @type String  11  */  12  this.name = name;  13  /**  14  * @property items  15  * @type Object  16  * @default {}  17  */  18  this.items = {};  19 }; 

There’s not really anything new here: notice that we’re declaring that the default (or initial) state of the items property is an empty object.

Now, the methods. For the addItem, one of the parameters is optional, so we declare it as so, and give it a default value of 1. Also, notice that we make the method @chainable.

 1 /**  2  * Adds 1 or more of a given item to the cart, if the chosen quantity  3  * is available. If not, none are added.  4  *  5  * @method addItem  6  * @param item {Object} An Item Object  7  * @param [quantity=1] {Number} The number of items to add to the cart  8  * @chainable  9  */  10 11 Store.Cart.prototype.addItem = function (item, quantity) {  12  quantity = quantity || 1;  13  if (item.quantity >= quantity) {  14  this.items[item.id] = this.items[item.id] || 0;  15  this.items[item.id] += quantity;  16  item.quantity -= quantity;  17  }  18  return this;  19 }; 

Finally, we want to be able to return the total price, including taxes. Notice that we’re doing the price math in cents, and then converting to dollars and rounding to two decimal places.

 1 /**  2  * @method total  3  * @return {Number} tax-included total value of cart contents  4  */  5 6 Store.Cart.prototype.total = function () {  7  var subtotal, id;  8  subtotal = 0;  9  for (id in this.items) {  10  if(this.items.hasOwnProperty(id)) {  11  subtotal += Store.Item.list[id].price * this.items[id];  12  }  13  }  14  return parseFloat(((subtotal * (1 + Store.TAX_RATE / 100)) / 100).toFixed(2));  15 }; 

If you want to test this code out, here are a simple tests:

 1 var apple, pear, book, desk, assertEquals;  2 3 assertEquals = function (one, two, msg) {  4  console.log(((one === two) ? "PASS : " : "FAIL : ") + msg);  5 };  6 7 apple = new Store.Item('Granny Smith Apple', 1.00, 5);  8 pear = new Store.Item('Barlett Pear', 2.00, 3);  9 book = new Store.Item('On Writing Well', 15.99, 2);  10 desk = new Store.Item('IKEA Gallant', 123.45, 1);  11 cart = new Store.Cart('Andrew');  12 13 cart.addItem(apple, 1).addItem(book, 3).addItem(desk, 1);  14 15 assertEquals(apple.quantity, 4, "adding 1 apple removes 1 from the item quantity");  16 assertEquals(book.quantity, 2, "trying to add more books than there are means none are added");  17 assertEquals(cart.total(), 140.63, "total price for 1 apple and 1 desk is 140.63"); 

## Generating the Documentation

Now that we’ve written the code and comment blocks, it's time to generate the documentation.

If you’ve installed it globally via npm, you’ll be able to simply run yuidoc {path to js}. In my case, that’s

 1 yuidoc . 

Now, you’ll see that you have an out directory in that folder; open out/index.html, and you’ll see the documentation. Here’s what part of the Cart class documentation will look like:

## Configuring Output

There are several configuration options you can set when using YUIDoc. Sure, you can set them as command line flags, but I’d rather set them in a JSON config file. In your project directory, create a file named yuidoc.json. First, there’s a bunch of general project information you can set; this doesn’t really effect the output too much, but it's good to document them:

 1 {  2  "name": "Documenting JavaScript with YUIDoc",  3  "description": "A tutorial about YUIDoc, for Nettuts+",  4  "version": "1.0.0",  5  "url": "https://code.tutsplus.com"  6 } 

Then, there are a number of actual options you can set. Here are a couple of interesting ones;

• linkNatives: set this to “true” to link native types like String or Number to the MDN docs.
• outdir: use this one to rename the out directory
• paths: use this to set which paths YUIDoc searches for JavaScript files.
• exclude: set this to a comma-separated list of files you want YUIDoc to ignore.

As long as you set the paths options, you can run yuidoc -c yuidoc.json and YUIDoc will run. Even if you don’t set paths and just run yuidoc ., YUIDoc will see that config file and apply it.

Here’s my total config file for this project:

 1 {  2  "name": "Documenting JavaScript with YUIDoc",  3  "description": "A tutorial about YUIDoc, for Nettuts+",  4  "version": "1.0.0",  5  "url": "https://code.tutsplus.com",  6  "options": {  7  "linkNatives": "true",  8  "outdir": "./docs",  9  "paths": "."  10  }  11 } 

## Evaluation

Based on the tags YUIDoc offers, you can see that it was made for JavaScript written in traditional OOP style, as well as specially for YUI widgets and such (in fact, I’ve left out several tags that were YUI-specific). Because of all this, you might find that several tags just aren’t that useful to you. Then, you have to ask yourself whether you’re willing to change your coding style to better match the way YUIDoc “thinks.” But even if you aren’t going to change, I think you’ll find that most YUIDoc tags will fit in just fine.

The bigger question to me is whether you like to have your documentation inline with your code.

The example code we wrote above is 120 lines with comments, 40 lines without. Obviously, that’s super simple code, and pretty much any real world example would be more balanced; however, reading such interspersed code could be difficult. Personally, I think I’m going to give YUIDoc a fair trial: I’ll be documenting my JavaScript as I write it (or at least, along side it) for the next few weeks. I’ll be interested to see if or how it affects my coding style and workflow.

You know the routine: love it or hate it, let me know in the comments!