Sub topic 1
Anatomy of a JSDoc Comment
JSDoc is a convention for writing structured comments above JavaScript code. Tools read these comments to build documentation, power editor hints, and check types.
Prerequisites
This chapter assumes you can write JavaScript functions and objects, and that you use an editor such as VS Code. You do not need TypeScript experience.
The Comment Block
A JSDoc comment starts with /** (two asterisks) and ends with */. A comment that starts with /* or // is ignored by JSDoc tools. The block must sit directly above the code it describes.
Inside the block, free text comes first and forms the description. Tags follow. A tag is a keyword starting with @ that adds a specific kind of information.
Parameters and Return Values
@param {type} name - description documents one parameter. Wrap the name in square brackets to mark it optional, and add =value to record its default. @returns {type} describes what the function gives back.
/**
* Calculates a price including tax.
* @param {number} price - The base price.
* @param {number} [taxRate=0.2] - Tax rate as a fraction.
* @returns {number} The price with tax applied.
*/
function withTax(price, taxRate = 0.2) {
return price * (1 + taxRate);
}
console.log(withTax(100)); // 120A common error is a parameter name in the tag that does not match the real name in the function, for example after a rename. Tools then report a missing or unknown parameter.
Type Expressions
The text inside the braces is a type expression. The most common forms are:
| Syntax | Meaning | Column |
|---|---|---|
| `{string}` | A primitive type | |
| `{string \ | number}` | A union: either type |
| `{string[]}` or `{Array<string>}` | An array of strings | |
| `{{x: number, y: number}}` | An inline object shape | |
| `{?string}` | Nullable: a string or `null` | |
| `{*}` | Any type |
Exercise
Write a JSDoc block for function label(point, prefix = "P"), where point is an object with numeric x and y, prefix is an optional string, and the function returns a string.
Show answer
/* Formats a point as a label. @param {{x: number, y: number}} point - The point to format. @param {string} [prefix="P"] - Text placed before the coordinates. @returns {string} The formatted label. /