Comments and documentation
suggest changeJavaScript has two kinds of comments, // and /* */. On top of that the Node.js ecosystem has a convention, JSDoc, for structured comments that describe functions, parameters and types. JSDoc comments are read by people, by editors (VS Code shows them on hover and uses them for autocomplete), by the TypeScript compiler (which can type-check plain .js files against them) and by documentation generators.
This article covers:
- comment syntax and its gotchas
- what to write in comments
- JSDoc tags for functions, objects and modules
- type-checking JavaScript with JSDoc and
tsc - generating
.d.tsfiles and HTML documentation - deprecating an API, both in docs and at runtime
- comments that tools treat as instructions
The examples were run with Node.js 24, TypeScript 7.0 and jsdoc 4.0, in a project whose package.json has "type": "module".
Comment syntax
#!/usr/bin/env node
// A single-line comment runs to the end of the line.
/*
A block comment can span
several lines.
*/
const total = 10 /* inline block comment */ + 5;
console.log(total); // trailing comment
const url = 'https://example.com/a//b'; // "//" inside a string is not a comment
console.log(url);
const re = /\/\*.*\*\//; // a regex that matches "/* ... */"
console.log(re.test('x /* y */ z'));
// Block comments don't nest:
/* outer /* inner */
console.log('still running');
15
https://example.com/a//b
true
still running
The first line, #!/usr/bin/env node, is a hashbang. It's only allowed as the very first line of a file. On Unix it tells the shell which program runs the script, so after chmod +x you can run ./basics.js directly. Node.js (and the JavaScript standard since ES2023) treats it as a comment. The bin scripts of npm packages start with it.
The last example shows the most common block comment trap. /* inside a block comment is just text, and the comment ends at the first */. Commenting out code that already contains a block comment breaks it:
import vm from 'node:vm';
const code = `
/* commenting out a block that already has a comment:
const a = 1; /* the answer */
const b = 2;
*/
`;
try {
new vm.Script(code);
} catch (err) {
console.log(err.name + ': ' + err.message);
}
SyntaxError: Unexpected token '*'
The comment ended after the answer */, so const b = 2; became code and the final */ a syntax error. To disable a chunk of code, use // on each line (editors do this with Ctrl+/ or Cmd+/), or better, delete it. Git remembers it.
Comments are kept in the function source. Function.prototype.toString() returns the original text including comments, which is why minifiers strip them for code sent to browsers. In Node.js they cost nothing at runtime beyond parsing.
function add(a, b) {
// adds two numbers
return a + b;
}
console.log(add.toString());
function add(a, b) {
// adds two numbers
return a + b;
}
What to write in comments
Code says what the program does. Comments should say what the code can't: why it does it this way, what the constraints are, and what would go wrong if you changed it.
// Bad: repeats the code
// increment retries by one
retries++;
// Good: explains a decision that isn't visible in the code
// The payment API rate-limits to 10 req/s per key and returns 429 without
// a Retry-After header, so back off ourselves: 200 ms, 400 ms, 800 ms...
await sleep(200 * 2 ** retries);
// Good: warns about a non-obvious trap
// Don't replace with fs.rm(): on Windows, antivirus scanners briefly lock
// new files and rm fails with EBUSY. rmWithRetry() retries for 2 seconds.
await rmWithRetry(tmpDir);
Some guidelines:
- If you need a comment to explain what a block does, consider turning the block into a function whose name says it:
if (isEligibleForFreeShipping(order))instead of a comment above a three-line condition. - Link to the source of non-obvious knowledge: a bug tracker issue, an RFC section, a Stack Overflow answer.
- Mark unfinished work with a consistent tag,
TODO,FIXMEorHACK, ideally with an issue number:// TODO(#482): handle paginated responses. Editors highlight them andgrep -rn "TODO" srcfinds them all. - A wrong comment is worse than none. When you change code, update the comments around it.
- Don't comment out code "for later". Delete it; version control keeps the history.
JSDoc comments
A JSDoc comment starts with /** (two asterisks) and sits directly before the thing it documents. The first paragraph is the description; lines starting with @ are tags.
Here is a small module, src/cart.js, documented with the most useful tags:
/**
* Shopping cart helpers.
* @module cart
*/
/**
* One line in a shopping cart.
* @typedef {object} CartItem
* @property {string} sku - Stock keeping unit, e.g. "BOOK-42".
* @property {number} price - Unit price in cents.
* @property {number} [quantity=1] - How many units; defaults to 1.
*/
/**
* Computes the total price of a cart in cents.
*
* Prices are kept in integer cents so that sums are exact;
* `0.1 + 0.2` is not `0.3` in floating point.
*
* @param {CartItem[]} items - The cart contents.
* @param {object} [options]
* @param {number} [options.discount=0] - Discount as a fraction, 0 to 1.
* @returns {number} Total in cents, rounded to the nearest cent.
* @throws {RangeError} If `discount` is outside 0..1.
* @example
* cartTotal([{ sku: 'A', price: 1999, quantity: 2 }], { discount: 0.1 });
* // => 3598
*/
export function cartTotal(items, { discount = 0 } = {}) {
if (discount < 0 || discount > 1) {
throw new RangeError(`discount must be between 0 and 1, got ${discount}`);
}
const sum = items.reduce((acc, it) => acc + it.price * (it.quantity ?? 1), 0);
return Math.round(sum * (1 - discount));
}
/**
* Formats cents as a currency string.
* @param {number} cents
* @param {string} [currency='USD'] - ISO 4217 currency code.
* @returns {string}
*/
export function formatCents(cents, currency = 'USD') {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}
And a program using it, main.js:
import { cartTotal, formatCents } from './src/cart.js';
const items = [
{ sku: 'BOOK-42', price: 1999, quantity: 2 },
{ sku: 'PEN-1', price: 250 },
];
const total = cartTotal(items, { discount: 0.1 });
console.log(total, formatCents(total));
try {
cartTotal(items, { discount: 10 });
} catch (err) {
if (!(err instanceof RangeError)) throw err;
console.log(`${err.name}: ${err.message}`);
}
3823 $38.23
RangeError: discount must be between 0 and 1, got 10
The tags you'll use most:
| Tag | Meaning |
|---|---|
@param {type} name - text |
a parameter; [name] marks it optional, [name=default] gives the default |
@param {type} options.key |
a property of an object parameter |
@returns {type} text |
the return value (@return also works) |
@throws {ErrorType} text |
when the function throws |
@typedef {object} Name with @property |
a named object shape you can reuse as a type |
@type {type} |
the type of a variable or constant |
@template T |
a generic type parameter |
@example |
example code, shown as a code block by doc generators and editors |
@deprecated text |
the API shouldn't be used any more |
@see, {@link name} |
references to other documentation |
@module name |
documents the file as a module |
Types inside the braces use TypeScript syntax: string, number[], Array<string>, string | null, Promise<User>, Record<string, number>, (err: Error | null, data?: Buffer) => void, 'asc' | 'desc'.
Don't write a @param that only repeats the parameter name (@param {string} name - The name). The type is useful on its own; add a description when it says something new, such as the unit (cents), the range (0 to 1) or the format ("BOOK-42").
In VS Code, typing /** above a function and pressing Enter generates a skeleton with a @param line for each parameter.
Type-checking JavaScript with JSDoc
The TypeScript compiler understands JSDoc types in plain .js files. You get most of TypeScript's error checking without a build step: the code Node.js runs is exactly the code you wrote.
Install TypeScript and Node's type definitions as dev dependencies:
npm install --save-dev typescript @types/node
To check a single file, put // @ts-check at its top. Editors with TypeScript support (VS Code out of the box) then underline errors as you type. Here's a file with four bugs that Node.js would happily run:
// @ts-check
import { cartTotal, formatCents } from './src/cart.js';
const items = [{ sku: 'BOOK-42', price: 1999 }];
const total = cartTotal(items, { discout: 0.1 });
console.log(formatCents(total, 840));
console.log(cartTotal([{ sku: 'PEN-1', price: '2.50' }]));
console.log(formatCents(total).lenght);
npx tsc --noEmit --allowJs --module nodenext --target es2024 checkout.js
checkout.js(5,34): error TS2561: Object literal may only specify known properties, but 'discout' does not exist in type '{ discount?: number | undefined; }'. Did you mean to write 'discount'?
checkout.js(7,32): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
checkout.js(8,40): error TS2322: Type 'string' is not assignable to type 'number'.
checkout.js(9,32): error TS2551: Property 'lenght' does not exist on type 'string'. Did you mean 'length'?
Every one of those comes from the JSDoc in cart.js. Without the checker, the misspelled discout silently gives no discount, '2.50' * 1 quietly becomes 2.5, and lenght is undefined. Only the bad currency code fails at runtime, with RangeError: Invalid currency code : 840.
For a whole project, add a tsconfig.json (VS Code also accepts jsconfig.json) instead of per-file comments:
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true,
"module": "nodenext",
"target": "es2024",
"types": ["node"]
},
"include": ["src", "main.js"]
}
checkJs checks every .js file as if it had // @ts-check, noEmit means tsc only checks and writes no files, and strict turns on the stricter checks such as null handling. Run it with npx tsc, or add "check": "tsc" to scripts in package.json and run it in CI next to your tests.
strict is worth having, but expect it to find things. On the first version of main.js, which had console.log(err.message) in the catch block, it reported:
main.js(14,18): error TS18046: 'err' is of type 'unknown'.
main.js(14,31): error TS18046: 'err' is of type 'unknown'.
JavaScript can throw any value, not just Error objects, so a caught value is unknown until you check it. That's why main.js above has the instanceof RangeError test.
Generics, imported types and casts
@template declares type parameters, @import brings in types from another module without a runtime import, and @type annotates variables:
/** @import { CartItem } from './cart.js' */
/**
* Returns the first element matching `pred`, or throws.
* @template T
* @param {T[]} list
* @param {(item: T) => boolean} pred
* @returns {T}
*/
export function findOrThrow(list, pred) {
const found = list.find(pred);
if (found === undefined) throw new Error('not found');
return found;
}
/** @type {CartItem[]} */
const stock = [
{ sku: 'BOOK-42', price: 1999 },
{ sku: 'PEN-1', price: 250, quantity: 100 },
];
/** @type {Map<string, number>} */
const priceBySku = new Map(stock.map((it) => [it.sku, it.price]));
const pen = findOrThrow(stock, (it) => it.sku === 'PEN-1'); // pen is CartItem
console.log(pen.quantity, priceBySku.get('BOOK-42'));
/** @satisfies {Record<string, number>} */
const limits = { maxItems: 50, maxQuantity: 10 };
console.log(limits.maxItems);
100 1999
50
Because findOrThrow is generic, the checker knows pen is a CartItem and that findOrThrow([1, 2, 3], ...) returns a number. Adding pen.qty; and findOrThrow([1, 2, 3], (x) => x > 1).toUpperCase(); to the file gives:
src/inventory.js(31,5): error TS2339: Property 'qty' does not exist on type 'CartItem'.
src/inventory.js(31,60): error TS2339: Property 'toUpperCase' does not exist on type 'number'.
@satisfies checks that a value matches a type while keeping its more precise inferred type, so limits.maxItems is still known to exist.
Types are not runtime checks
JSDoc types, like TypeScript types, disappear when the code runs. They protect code that's checked by tsc, not callers who use your package from unchecked JavaScript or pass data parsed from JSON. Validate input at the boundaries of your program (HTTP handlers, CLI arguments, config files, public library functions) in code.
// @ts-expect-error tells the checker that the next line is expected to have a type error, for example in a test that deliberately passes bad input. Unlike // @ts-ignore, it reports an error when the line becomes correct, so stale suppressions don't pile up:
// @ts-check
import { cartTotal } from './src/cart.js';
// @ts-expect-error -- plain JS callers can still pass a string
console.log(cartTotal([{ sku: 'A', price: 100 }], { discount: '0.5' }));
// @ts-expect-error
console.log(cartTotal([{ sku: 'A', price: 100 }]));
directives.js(7,1): error TS2578: Unused '@ts-expect-error' directive.
Running it shows the point of the previous paragraph: the string discount isn't rejected, because '0.5' < 0 and '0.5' > 1 coerce the string to a number.
50
100
If discount can come from untyped callers, cartTotal should check typeof discount !== 'number' itself.
Generating type declarations
When you publish a package written in JavaScript, users writing TypeScript (and all VS Code users) benefit from .d.ts declaration files. tsc generates them from your JSDoc. Add tsconfig.types.json:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "types"
},
"include": ["src"]
}
npx tsc -p tsconfig.types.json
This writes types/cart.d.ts. The JSDoc descriptions are copied over, so they show up in editors of people using your package (the long JSDoc comments are shortened here):
/**
* Shopping cart helpers.
* @module cart
*/
export type CartItem = {
/**
* - Stock keeping unit, e.g. "BOOK-42".
*/
sku: string;
/**
* - Unit price in cents.
*/
price: number;
/**
* - How many units; defaults to 1.
*/
quantity?: number;
};
/**
* Computes the total price of a cart in cents.
* ...
*/
export declare function cartTotal(items: CartItem[], { discount }?: {
discount?: number;
}): number;
/**
* Formats cents as a currency string.
* ...
*/
export declare function formatCents(cents: number, currency?: string): string;
Point to them from package.json with "types": "./types/cart.d.ts" (or a types condition in exports), and generate them in a prepublishOnly script. See Publishing a package.
Documentation in TypeScript files
Node.js 24 runs .ts files directly by stripping type annotations, so many projects now write TypeScript without a build step. In TypeScript the types are in the code, so doc comments drop the {type} part and only describe. This style is called TSDoc:
/**
* Converts a title into a URL slug.
*
* @param title - Any text, e.g. an article title.
* @param maxLength - Slugs longer than this are cut at a word boundary.
* @returns Lowercase ASCII words joined with "-".
*
* @example
* ```ts
* slugify('Comments & Documentation in Node.js'); // 'comments-documentation-in-node-js'
* ```
*/
export function slugify(title: string, maxLength = 60): string {
const slug = title
.normalize('NFKD')
.replace(/\p{M}/gu, '') // drop accents: "é" -> "e"
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
if (slug.length <= maxLength) return slug;
return slug.slice(0, slug.lastIndexOf('-', maxLength)); // don't cut words in half
}
console.log(slugify('Comments & Documentation in Node.js'));
console.log(slugify('Café déjà vu'));
console.log(slugify('a very long title that goes on and on', 20));
node slug.ts
comments-documentation-in-node-js
cafe-deja-vu
a-very-long-title
Writing {string} in a .ts file's doc comment is redundant and can drift from the real type; let the signature carry the types.
Generating HTML documentation
The jsdoc package turns JSDoc comments into a static HTML site:
npm install --save-dev jsdoc
npx jsdoc src -r -d docs
-r recurses into subdirectories and -d sets the output directory. With just cart.js in src/, the result has an index.html and one page per module (module-cart.html) listing CartItem, cartTotal and formatCents with their parameters, return values, @throws and @example code. Pass a README.md as an extra argument to use it as the front page.
jsdoc -X prints the parsed comments as JSON instead, which is handy for checking what the tool understood, or for writing your own documentation tooling:
// list-docs.js: npx jsdoc src -X | node list-docs.js
let json = '';
process.stdin.on('data', (chunk) => (json += chunk));
process.stdin.on('end', () => {
for (const doc of JSON.parse(json)) {
if (doc.undocumented || doc.kind === 'package') continue;
const params = doc.params ? doc.params.map((p) => p.name).join(', ') : '';
console.log(doc.kind.padEnd(9), doc.longname, params);
}
});
module module:cart
typedef module:cart~CartItem
function module:cart.cartTotal items, options, options.discount
function module:cart.formatCents cents, currency
The jsdoc tool doesn't understand TypeScript syntax. Once src/ also contains the inventory.js file from earlier, npx jsdoc src -r -d docs still writes the pages, but exits with code 1 and prints ERROR: Unable to parse a tag's type expression ... Invalid type expression "(item: T) => boolean". For TypeScript projects, or JavaScript projects that use TypeScript-only JSDoc syntax like arrow function types or @import, use TypeDoc (npx typedoc src/index.ts), which reads the same comments through the TypeScript compiler.
Many libraries skip generated HTML and document their API in README.md, which npm and GitHub display. A good README answers, in this order: what the package does, how to install it, a short working example, the API reference (or a link to it), and supported Node.js versions.
Keep examples working
Examples in documentation rot quietly when the code changes. A cheap fix is a test that runs each documented example:
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cartTotal } from './src/cart.js';
// Keep the @example in cartTotal's JSDoc in sync with this test.
test('cartTotal @example', () => {
assert.equal(cartTotal([{ sku: 'A', price: 1999, quantity: 2 }], { discount: 0.1 }), 3598);
});
test('cartTotal rejects a discount above 1', () => {
assert.throws(() => cartTotal([], { discount: 1.5 }), RangeError);
});
node --test --test-reporter=spec cart.test.js
✔ cartTotal @example (0.5123ms)
✔ cartTotal rejects a discount above 1 (0.2746ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 53.0095
Deprecating an API
@deprecated marks an API as obsolete in the docs. Editors show calls to it struck through. To also warn people who don't read the docs, wrap the function with util.deprecate(), which prints a warning the first time it's called:
import { deprecate } from 'node:util';
/**
* Returns the total price in dollars.
* @deprecated Since 2.0. Use {@link cartTotal}, which returns cents.
* @param {number[]} prices
* @returns {number}
*/
export const totalDollars = deprecate(
(prices) => prices.reduce((a, b) => a + b, 0),
'totalDollars() is deprecated, use cartTotal() instead',
'CART001',
);
console.log(totalDollars([1.5, 2.5]));
console.log(totalDollars([3])); // the warning is printed only once
4
3
(node:3636) [CART001] DeprecationWarning: totalDollars() is deprecated, use cartTotal() instead
(Use `node --trace-deprecation ...` to show where the warning was created)
The warning goes to stderr. The third argument is a code; Node prints a given code only once per process, even if several functions share it. Users control these warnings with flags: --no-deprecation silences them, --trace-deprecation adds a stack trace showing the caller, and --throw-deprecation turns them into exceptions, which is useful in test runs to catch deprecated calls early.
Comments that tools read
Some comments are instructions to tools rather than notes to people:
| Comment | Read by | Effect |
|---|---|---|
#!/usr/bin/env node |
the OS shell | runs the file with Node.js |
// @ts-check, // @ts-nocheck |
TypeScript, editors | turn type checking on or off for the file |
// @ts-expect-error, // @ts-ignore |
TypeScript | suppress an error on the next line |
// eslint-disable-next-line no-console |
ESLint | skip a rule for the next line |
/* node:coverage ignore next */ |
node --test --experimental-test-coverage |
exclude the next line from coverage |
/* c8 ignore next */ |
the c8 coverage tool | the same for c8 (Node's own coverage ignores it) |
//# sourceMappingURL=app.js.map |
Node.js, browsers | points to a source map for stack traces |
/*#__PURE__*/ |
bundlers and minifiers | marks a call as side-effect free, so it can be removed if unused |
Always give the reason when you suppress a check: // eslint-disable-next-line no-await-in-loop -- requests must be sequential, the API rejects parallel calls. ESLint ignores the text after --, and it tells the next reader the suppression was deliberate.
Comments in JSON files
JSON has no comments, so package.json can't have them, and JSON.parse() rejects them:
const text = `{
// port to listen on
"port": 8080
}`;
try {
JSON.parse(text);
} catch (err) {
console.log(err.message);
}
Expected property name or '}' in JSON at position 4 (line 2 column 3)
npm ignores a top-level "//" key in package.json, so it's the conventional place for a note:
{
"name": "shop",
"version": "1.0.0",
"type": "module",
"//": "express is pinned to 4.x until the router migration (#123) is done",
"dependencies": {
"express": "^4.21.2"
}
}
Don't put "//" inside scripts: npm run lists it as a script. tsconfig.json is different: TypeScript parses it as JSONC, which allows // and /* */ comments, as do VS Code's settings files. For your own config files that people edit by hand, prefer a format with comments; see Configuration files.
Summary
- Use
//for comments and keep/* */for JSDoc and short inline notes; block comments don't nest. - Comment the why: decisions, constraints, traps and links. Delete commented-out code.
- Document exported functions with
/** */JSDoc: types, units, ranges, errors and an@example. - Add
checkJs(or// @ts-check) and runtscin CI to turn JSDoc types into real error checking, and still validate untrusted input at runtime. - Generate
.d.tsfiles for published packages, HTML docs withjsdocor TypeDoc, and test your examples. - Deprecate with
@deprecatedplusutil.deprecate()so both readers and running code get the message.