JavaScript – Documenting optional parameter

JavaScript is an awesome language but due to its nature parameter documentation is pretty important especially when it come to optional parameters. If you want to create a method like this:

module.exports.create = function (callback) {
    // Do something
    if (callback) {
        callback();
    }
}

Obviously, callback is an optional parameter but if we use this method in an IDE like JetBrains WebStorm it will always show us a wrong signature warning and other developers might think this parameter is mandatory.  We can overcome that situation by adding the correct comment on this method.

/**
 * The method does something. 
 * 
 * @param {requestCallback=} callback
 */
module.exports.create = function (callback) {
    // Do something
    if (callback) {
        callback();
    }
}

Now the IDE and other developers looking at our method know that the parameter is optional and can use it like that. This syntax can be used to provide a lot of information on the different request parameter. This link contains a very detailed description.

Advertisements