Using JSDoc to write better JavaScript Code
Tags: javascript, webdev, programming, typescript
Published: 2021-11-26 08:28:30

Using [TypeScript](https://www.typescriptlang.org) consistently offers a lot of benefits, especially for writing clean code to prevent unnecessary bugs and errors. But it takes some time and effort to learn, and you have to adapt every code snippet after copy-pasting from a tutorial or a StackOverflow example. Quite a challenge when re-using code for React, Node, Express and Mongoose like I did in my [full-stack web app side project](https://dev.to/ingosteinke/building-a-reading-list-web-app-with-node-preact-and-tailwind-css-44pa).

## Alternatives to TypeScript

* Popular, but unhelpful, alternative: don't care at all.

* Use [eslint](https://eslint.org), but that's not an alternative. With or without strong typing, you should lint your code anyway to benefit from (mostly) helpful hints and warnings.

* [ReactPropTypes](https://reactjs.org/docs/typechecking-with-proptypes.html) add some type checking to ECMAScript / JavaScript in React applications, but PropTypes are merely footnotes, placed far away from where they would be most useful, while still bloating your code.

  ![PropTypes example with an unhappy emoji and critical handwritten notes reading: merely a footnote below?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqvq8jwf73jucyf7r2p3.png)

  And there are no PropTypes in [Vanilla JS](#writing-clean-modern-vanilla-js-code).

* enter **JSDoc**:

## JSDoc

Often overlooked, maybe never even heard of until now, [JSDoc](https://jsdoc.app/) deserves more attention, as it brings a lot of advantages out of some short lines of documentation.

### Code Documentation

That's JSDoc's original purpose: generating a code / API documentation out of a few lines placed before variables, functions, and classes.

Similar approaches have been used with Java and PHP for a long time, and JSDoc follows established practice and is quite easy to learn.

### Hints and Code Completion

Using JSDoc inside a modern IDE, you'll get another benefit: live code inspection, warnings, and proper code completion even for the most obscure DOM methods you never knew about before. Or well-known classics like `event.currentTarget` that still have some tricky pitfalls.

Here is a - seemingly simple - example: 

![Screenshot of annotated code with method hints in PhpStorm IDE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o65lra697a5k7tzv69p3.png)

I wanted to allow a modal dialog to be closed typing the Escape key. My first quick code-like-it's-1999-style script (not shown here) was frowned upon by eslint. ☹️

### Writing Clean, Modern Vanilla JS Code

So I decided to write proper, modern code, but still plain "Vanilla JS" (that does not need a transpiler to produce working code, unlike TypeScript, which does not have native browser support, not even in Microsoft's Edge browser).

I wrote a function that takes two arguments: an event, and an optional DOM element so that we are able to close a specific modal dialog from outside without relying on the event context.

Adding a JSDoc comment before, it becomes

```js
/**
 * close an open modal dialog
 * @param {MouseEvent} event
 * @param {HTMLElement=} elementToClose
 */
const modalClose = function modalClose(event, elementToClose) {
  // ...
};
```

telling my readers (of this code, and of a possible, automatically generated, documentation / API reference) what the function is supposed to do, and what arguments it expects:

`@param {MouseEvent} event`

Now my IDE (PhpStorm) will show me helpful information:

![Screenshot of the annotated MouseEvent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aiyn5varte2ompdiy7sj.png)

I don't even have to look up the proper type string to write in the JSDoc comment!

When I start typing, PhpStorm has some suggestions for code completion even in this special kind of comment, suggesting `MouseEvent` on top of the list.

![Screenshot showing a dropdown with suggested type annotations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htndxj29letruyom1mke.png)

## JSDoc Syntax

The basic syntax is rather simple.

Annotations blocks are special comments that start with a slash and a double asterisk `/**`

A parameter hint starts with an at sign, the word "param", and a type definition inside curly braces, followed by the parameter's name.

To mark an optional parameter, add an equals sign behind the type, like 

```js
@param {HTMLElement=} elementToClose
```

but to be more clear to human readers, we can also add anything behind the parameter's name, like

```js
@param {HTMLElement=} elementToClose (optional) DOM element to receive .closed CSS class
```

Now my editor shows me type annotations, that are not part of my written code (unlike they would be in TypeScript) but rather implicitly follow from my code. So my actual code stays short and compact, while the implicit meaning is still more obvious than before.

### Assistance for Lazy Developers

Not only do we see the additional hint `event: MouseEvent`, but when we start using the `event` in our code below, there are more code suggestions, helping us to choose methods and properties that are actually available and not deprecated.

![Image showing code completion suggestions for 'event.' in PhpStorm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zul8g46vxu3cfzkdseux.png)

More assistance as we continue: hints and documentation everywhere. We don't even have to visit [MDN](https://developer.mozilla.org/) in our browser anymore!

![Screenshot showing documentation for event.currentTarget.closest](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsadm8d4rwn9l7d77h61.png)

## Conclusion

JSDoc makes coding in JavaScript easier, helping us to code quickly while avoiding obvious errors, just by adding some lines of optional comments in our code.