[JSDoc] How to annotate like a JavaScript Pro
What is JSDoc?
JSDoc is a markup language used to annotate JavaScript source code files. Using comments containing JSDoc, programmers can add documentation describing the application programming interface of the code they're creating.
How to use JSDoc?
You need to add comments between /** ... */
to use JSDoc. Then JSDoc can give you type hints to variables and functions.
Variable type
/** @type {string} */ let str; /** @type {number} */ let num; /** @type {boolean} */ let bool; /** @type {*} */ let any; /** @type {?} */ let unknown; /** @type {number[]} */ let nums; /** @type { {id: number, content: string, completed: boolean} } */ let obj; /** @type {string|number} */ let union; /** @type {Array<{ id: number, content: string, completed: boolean }>} */ let generic;
Function type
/** * Clamp a value * @param {number} value The value to clamp * @param {number} min * @param {number} max */ function clamp(value, min, max) { return Math.min(Math.max(value, min), max); }
It will look like this when you hover the function clamp!
Can also use,
@version
to show the version of the function, like@version 1.3.0
@see
to attach URL for reference, like@see https://naver.com
@todo
to mark todo memo, like@todo fix this function
@deprecated
to warn to stop using this function, like@deprecated stop using this function!
Also, If @ts-check
is added as a comment(like, // @ts-check
) to the first line in the pure JavaScript source code, type and error checks are possible like TypeScript.
Why do people use JSDoc?
Yes, we have a TypeScript which is the perfect replacement for JSDoc! But, people use JSDoc because TypeScript is too strict also the conversion from TypeScript to JavaScript takes time, increases the amount of code and can mess up the code.
Subscribe to my newsletter
Read articles from Jiwon Yu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by