JSDoc refers to JavaScript documentation through comment blocks, it is similar to the JavaDoc. With it, it is possible to type-check your JavaScript code and avoid setting up a build/compilation step in your project. This method still requires TypeScript, but only for developing, not to ship your code.
If you’re building a frontend application using a library like React, you will probably use a tool such as Webpack (or Vite) to bundle/compile your code into JavaScript that browsers can understand. In that case, you might as well use TypeScript because you already have a build step. Though, if you think the Hot Reloading or the build step is too slow, JSDoc could still be of help.
Now if you’re building a library, then JSDoc becomes really attractive. It allows you to document your library and type-check your code without requiring you to have a build step. You can focus on coding then publish your library as-is.
Let’s dive into an example to help you understand how type-checking with JSDoc works.
/**
* Iterates over elements of array and invokes function for each element
* @template T the type of the array's elements
* @param {T[]} arr the array to iterate over
* @param {(element: T) => void} fn the function invoked per iteration
*/
function forEach(arr, fn) {
for (let i = 0; i < arr.length; i++) {
fn(arr[i]);
}
}
// Self-executing function
(() => {
const fruits = ["apple", "orange", "pear", "kiwi", "banana", "pineapple"];
forEach(fruits, (fruit) => {
console.log(fruit);
});
})();
#javascript #typescript #js #jsdoc #app