JavaScript DocBlock standard

Introduction

To add JavaScript code inline documentation, follow these guidelines. Some parts of Magento code may not comply with this standard, but we are working to gradually improve this. Following these standard is optional for 3rd-party Magento developers, but will help to create consistent, clean, and easy to read inline documentation. This standard are a subset of Google JavaScript Style Guide regulations.

Use RFC 2119 to interpret the "must," "must not," "required," "shall," "shall not," "should," "should not," "recommended," "may," and "optional" keywords.

Use JSDoc

Document all files, classes, methods, and properties with JSDoc comments.

Inline comments should be of the “//” type.

It is recommended to avoid sentence fragments in documentation blocks. Use sentence-style capitalization and put a period at the end. Sentence fragmentation is acceptable in inline commentaries to keep it short.

Comment syntax

JSDoc comments requirements:

  • A JSDoc comment should begin with a slash (/) and two asterisks (*).
  • Inline tags should be enclosed in braces: { @code this }.
  • @desc Block tags should always start on their own line.

Example:

/**
* A JSDoc comment should begin with a slash and 2 asterisks.
* Inline tags should be enclosed in braces like{@code this}.
* @desc Block tags should always start on their own line.
*/

Many tools extract metadata from JSDoc comments to validate and optimize the code.

JSDoc indentation

If you have to line break a block tag, you should treat this as breaking a code statement and indent it four spaces.

/**
 * Illustrates line wrapping for long param/return descriptions.
 *
 * @param {string} foo This is a param with a description too long to fit in
 *     one line.
 * @return {number} This returns something that has a description too long to
 *     fit in one line.
 */
project.MyClass.prototype.method = function(foo) {
    return 5;
};

Class comments

Classes must be documented with a description, and appropriate type tags.

/**
 * Class making something fun and easy.
 * @param {string} arg1 An argument that makes this more interesting.
 * @param {Array.<number>} arg2 List of numbers to be processed.
 * @constructor
 */
project.MyClass = function(arg1, arg2) {
    // ...
};

Method and function comments

A description must be provided along with parameters. Method descriptions should start with a sentence written in the third person declarative voice.

/**
 * Operates on an instance of MyClass and returns something.
 *
 * @param {project.MyClass} obj Instance of MyClass which leads to a long
 *     comment that needs to be wrapped to two lines.
 * @return {boolean} Whether something occured.
 */
function someMethod(obj) {
    // ...
}

Property comments

/**
 * Maximum number of things per pane.
 *
 * @type {number}
 */
project.MyClass.prototype.someProperty = 4;

JSDoc tag reference

@const

Marks a variable read-only and suitable for inlining. Generates warnings if it is rewritten. Constants should also be ALL_CAPS, but the annotation should help eliminate reliance on the naming convention.

/** @const */ var DEFAULT_TIMEZONE = 'GMT';
 
/** @const */ MyClass.DEFAULT_TIMEZONE = 'GMT';
 
/**
 * My namespace's default timezone.
 *
 * @const
 * @type {string}
 */
mynamespace.DEFAULT_TIMEZONE = 'GMT';

@extends

Used with @constructor to indicate that a class inherits from another class.

/**
 * Immutable empty node list.
 *
 * @constructor
 * @extends project.MyClass.BasicNodeList
 */
project.MyClass.EmptyNodeList = function() {
    // ...
};

@interface

Used to indicate that the function defines an interface.

/**
 * A shape.
 *
 * @interface
 */
function Shape() {};
Shape.prototype.draw = function() {};
 
/**
 * A polygon.
 *
 * @interface
 * @extends {Shape}
 */
function Polygon() {};
Polygon.prototype.getSides = function() {};

@implements

Used with @constructor to indicate that a class implements an interface.

/**
 * A shape.
 *
 * @interface
 */
function Shape() {};
Shape.prototype.draw = function() {};
 
/**
 * @constructor
 * @implements {Shape}
 */
function Square() {};
Square.prototype.draw = function() {
    // ...
};

@lends

Indicates that the keys of an object literal should be treated as properties of some other object. This annotation should only appear on object literals.

Please note that the name in braces is not a type name like in other annotations. It’s an object name. It names the object on which the properties are “lent”. For example, @type {Foo} means “an instance of Foo,” but @lends {Foo} means “the constructor Foo”.

Please refer to JSDoc Toolkit for more information about this annotation.

project.MyClass.extend(
    Button.prototype,
    /** @lends {Button.prototype} */ {
        isButton: function() {return true;}
    }
);

@override

Indicates that a method or property of a subclass intentionally hides a method or property of the superclass. If no other documentation is included, the method or property also inherits documentation from its superclass.

/**
 * @return {string} Human-readable representation of project.SubClass.
 * @override
 */
project.SubClass.prototype.toString() {
    // ...
};

@param

Used with method, function and constructor calls to document the arguments of a function.

Type names must be enclosed in curly braces. If the type is omitted, the compiler will not type-check the parameter.

/**
 * Queries a Storage for items.
 *
 * @param {number} groupNum Subgroup id to query.
 * @param {string|number|null} term An itemName,
 *     or itemId, or null to search everything.
 */
namespace.Storage.prototype.query = function(groupNum, term) {
   // ...
};

@return

Used with method and function calls to document the return type. When writing descriptions for boolean parameters, prefer “Whether the component is visible” to “True if the component is visible, false otherwise”. If there is no return value, do not use an @return tag.

Type names must be enclosed in curly braces. If the type is omitted, the compiler will not type-check the return value.

/**
 * @return {string} The hex ID of the last item.
 */
namespace.Storage.prototype.getLastId = function() {
    // ...
    return id;
};

@this

The type of the object in whose context a particular method is called. Required when the this keyword is referenced from a function that is not a prototype method.

pinto.chat.RosterWidget.extern('getRosterElement',
    /**
     * Returns the roster widget element.
     *
     * @this pinto.chat.RosterWidget
     * @return {Element}
     */
    function() {
        return this._getWrappedComponent().getElement();
    }
);

@type

Identifies the type of a variable, property, or expression.

/**
 * The message hex ID.
 *
 * @type {string}
 */
var hexId = hexId;

@typedef

This annotation can be used to declare an alias of a more complex type.

/** @typedef {(string|number)} */
namespace.NumberLike;
 
/** @param {namespace.NumberLike} x A number or a string. */
namespace.readNumber = function(x) {
    // ...
}

JavaScript types

Type example Value example Description
number
1
1.0
-5
1e5
Math.PI
Number
new Number(true)
Number object
string
'Hello'
"World"
String(42)
String value
String
new String('Hello')
new String(42)
String object
boolean
true
false
Boolean(0)
Boolean value
Boolean
new Boolean(true)
Boolean object
RegExp
new RegExp('hello')
/world/g
Date
new Date
new Date()
null
null
undefined
undefined
void
function f() {
	return;
}
No return value
Array
['foo', 0.3, null]
[]
Untyped Array
Array.<number>
[11, 22, 33]
An array of numbers
Array.<Array.<string>>
[['one', 'two', 'three'], ['foo', 'bar']]
Array of arrays of strings
Object
{}
{foo: 'abc', bar: 123, baz: null}
Object.<string>
{'foo': 'bar'}
An object. In the object, the values are strings.
Object.<number, string>
var obj = {};
obj[1] = 'bar';
An object. In the object, the keys are numbers and the values are strings. Note that in JavaScript, the keys are always implicitly converted to strings, so obj['1'] == obj[1]. So the key will always be a string in for...in loops. But the compiler will verify the type if the key when indexing into the object.
Function
function(x, y) {
	return x * y;
}
Function object
function(number, number): number
function(x, y) {
	return x * y;
}
function value
SomeClass
/** @constructor */
function SomeClass() {}
 
new SomeClass();
SomeInterface
/** @interface */
function SomeInterface() {}
 
SomeInterface.prototype.draw = function() {};
project.MyClass
/** @constructor */
project.MyClass = function () {}
 
new project.MyClass()
Element
document.createElement('div')
Elements in the DOM.
Node
document.body.firstChild
Nodes in the DOM.
HTMLInputElement
htmlDocument.getElementsByTagName('input')[0]
A specific type of DOM element.

JavaScript type language

</tr> </tbody> </table>
Operator name Syntax Description Deprecated syntaxes
Type Name {boolean}, {Window}, {namespace.ui.Menu} Simply the name of a type.
Type Application {Array. <string>}
An array of strings.
{Object. <string, number>}
An object. In the object, the keys are strings and the values are numbers.
Parametrizes a type, by applying a set of type arguments to that type. The idea is analogous to generics in Java.
Type Union {(number|boolean)}
A number or a boolean.
Indicates that a value might have type A OR type B. {(number,boolean)}, {number|boolean}, {(number||boolean)}
Record Type codemyNum: number, myObject}}
An anonymous type with the given type members.
Indicates that the value has the specified members with the specified types. In this case, myNum with a type number and myObject with any type. Note that the braces are part of the type syntax. For example, to denote an Array of objects that have a length property, you might write Array.<{length}>.
Nullable type {?number}
A number or NULL.
Indicates that a value is type A or null. By default, all object types are nullable. NOTE: Function types are not nullable. {number?}
Non-nullable type {!Object}
An Object, but never the null value.
Indicates that a value is type A and not null. By default, all value types (boolean, number, string, and undefined) are not nullable. {Object!}
Function Type {function(string, boolean)}
A function that takes two arguments (a string and a boolean), and has an unknown return value.
Specifies a function.
Function Return Type {function(): number}
A function that takes no arguments and returns a number.
Specifies a function return type.
Function this Type {function(this:namespace.ui.Menu, string)}
A function that takes one argument (a string), and executes in the context of a namespace.ui.Menu.
Specifies the context type of a function type.
Function new Type {function(new:namespace.ui.Menu, string)}
A constructor that takes one argument (a string), and creates a new instance of namespace.ui.Menu when called with the 'new' keyword.
Specifies the constructed type of a constructor.
Variable arguments {function(string, ...[number]): number}
A function that takes one argument (a string), and then a variable number of arguments that must be numbers.
Specifies variable arguments to a function.
Variable arguments (in @param/ annotations)</td> @param {...number} var_args
A variable number of arguments to an annotated function.
Specifies that the annotated function accepts a variable number of arguments.
Function optional arguments {function(?string=, number=)}
A function that takes one optional, nullable string and one optional number as arguments. The = syntax is only for function type declarations.
Specifies optional arguments to a function.
Function optional arguments (in @param annotations) @param {number=} opt_argument
An optional parameter of type number.
Specifies that the annotated function accepts an optional argument.
The ALL type {*} Indicates that the variable can take on any type.
The UNKNOWN type {?} Indicates that the variable can take on any type, and the compiler should not type-check any uses of it.