DEV Community

Functional Javascript
Functional Javascript

Posted on

Add JSDoc to your JavaScript Code

Documentation is important to keeping a codebase understandable as it grows in size, complexity, and innovation.

JSDOC is a documentation tool to help structure your documentation.

A Simple Example

A func definition that is annotated with JSDoc...

/**
@func
split a str composed of words into an arr of words

@tags
nlp

@notes
strips away single quotes that exist at the beginning or end of a word

@param {string} words
@return {string[]} the space-split words
*/
export const splitWord = words => words.match(/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g) || [];

A func that uses that splitWord func...


/**
@func
turns str into a URI conforming slug

@param {string} s - the str to be slugified
@return {string} the slugified str
*/
const getSlug = s => {
  return pipeStr(
    removeByRegex(/[\u0300-\u036f]/g), // removes diacritics, e.g. è -> e
    removeByRegex(/[^a-zA-Z0-9\s]/g), // only keep numbers and alphabet
    splitWord,
    joinByDash,
    getLowerCase,
  )(s);
};

Example Hover Tip

After the func's documentation is added, wherever you use the func, hit the hover tooltip shortcut and you'll get this JSDoc informative popup:

Alt Text

Set Shortcut Key

To activate the hover popup (called showDefinitionPreviewHover in VSC), first place your cursor on the func name, then hit the default shortcut keybinding (or you can create a custom keybinding). I have my custom binding set to cmd-n (ctrl-n)...

{
    "key": "cmd+n",
    "command": "editor.action.showDefinitionPreviewHover"
  },

What the Hover Popup informs you of

The Hover dialog will...

  • show you the function source code itself
  • the parameter types
  • the return type
  • the natural language documentation of the function, explaining what it does

How to set up JSDoc

See my prior post here...
https://dev.to/functional_js/quick-tip-setup-typescript-type-checking-with-your-pure-javascript-19ma

More coming soon

Stay tuned for more!

Top comments (2)

Collapse
 
juanfrank77 profile image
Juan F Gonzalez

So with this, I'll be able to move away from TS types into JSDoc types and still get the nice info & Intellisense I would get from regular Typescript? Sounds very good to me.

Also added bonus the fact that the tooltip shows the function's signature a la Haskell.

Collapse
 
functional_js profile image
Functional Javascript

Correct.

And you get all the type inferences and all the squigglies that Typescript gives you, while coding in pure JavaScript.

A strongly-typed design-time experience, with no transpiling step.