Sunday, February 28, 2021

JSDoc for Javascript Documentation

There are many ways for documenting a piece of code. For example you can write:

  • howtos guides for using your code
  • a nice README for the repo
  • code documentation in the source


Speaking of JavaScript, we can use a documentation layer called, JSDoc. It's a command line tool and a "documentation language" at the same time. Let's see how it can helps.


First thing first what's the anatomy of a JSDoc annotation? JSDoc is simple as adding a comment before the function:


But let's make things interesting with JSDoc annotations for function parameters. Here's the syntax:


/**

*

* @param {param type} param name - description

*

*/


  • its type, i.e. string, number, HTMLTableElement and so on
  • its name
  • description



Example is like below 


/**

 * Generates a table head

 * @param {HTMLTableElement} table - The target HTML table

 * @param {Array} data - The array of cell header names

 */

function generateTableHead(table, data) {

  const thead = table.createTHead();

  const row = thead.insertRow();

  for (const i of data) {

    const th = document.createElement("th");

    const text = document.createTextNode(i);

    th.appendChild(text);

    row.appendChild(th);

  }

}



Adding JSDoc documentation has a side effect. Auto completion will improve in your IDE and you'll get real-time hints:


Moreover, the editor will scream if you try to pass the wrong kind of parameters:

It might sound crazy, but adding JSDoc annotations before writing the code, not after, is another thing you can do. And it has two nice outcomes. First, you will probably write better, simpler code because of the idea of it you formed while writing the documentation.



Other samples are:


/**

 * Generates a table head

 * @author Valentino Gagliardi <valentinoDOTvalentinog.com>

 * @param {HTMLTableElement} table - The target HTML table

 * @param {Array} data - The array of cell header names

 */



/**

 * A silly logger function

 * @param {string} message

 * @return {void} Nothing

 */



/**

 * Raises a number to exponent

 * @param {number} value - The base to raise

 * @param {number} exponent - The exponent

 * @return {number} - The exponent power

 */



JavaScript With JSDoc: generating the docs


mkdir jsdoc-tutorial && cd $_

npm init -y

npm i jsdoc --save-dev


To run Jsdoc in entire directory, below to be done 


$ jsdoc -r .


This may needs to be installed globally to make it available entire system. 


Nam install -g jsdoc


References:

https://www.valentinog.com/blog/jsdoc/



Best Way to document Javascript 




References:

https://gomakethings.com/whats-the-best-way-to-document-javascript/

No comments:

Post a Comment