On this page
The short answerWhere examples and pages come fromBuild an illustrative projectSee what the scan can reachMake a scan-ready copyMake the expected behavior testableTriage the findingsPut the checks in the workflowWriting JSDoc examples a check can verifyThe sources we checkedFAQThe short answer
Build JSDoc, extract the examples it actually documents, and run checks that make expected behavior explicit. JSDoc displays example text as highlighted code; it does not run it or verify a result written in a comment. In engine 0.6.3, DocsAlive does not detect JSDoc or read source comments. With no top-level docs/ folder, its root scan reads the README and tutorials; once scan-docs/ exists, a root scan picks that up too. JavaScript fences run with Node, but their results and comments are never compared.
The workflow below uses JSDoc’s own JSON doclets to create a scan-ready page. A small rewrite turns one narrow returns-comment convention into an assertion. That gives an execution check something concrete to verify, while leaving other comments as comments. The package acme-units is illustrative and is not a published package.
Where examples and pages come from
The JSDoc example tag provides an example of using a documented item. The text after the tag is displayed as highlighted code. A doclet can have multiple examples, and a caption element immediately after a tag can provide a caption. Rendering those examples is useful to readers, but a successful documentation build says nothing by itself about whether a call still returns the value described beside it.
Source selection determines which doclets exist. source.include supplies paths. By default, source.includePattern selects files ending in .js, .jsdoc, or .jsx; the default source.excludePattern ignores files and folders beginning with an underscore. With recursive processing, the default recursion depth is 10. A file can therefore be present in the repository yet absent from the reference and from a JSON export made with the same configuration.
The -X or explain option prints doclets as JSON and exits. It is a useful boundary for an extraction script: the script can work from the material JSDoc reports rather than guessing how comments were parsed. It also inherits the configured source selection, so inspect that selection before treating the export as complete.
The README and tutorials are separate inputs. The readme option defaults to the first README.md found in the source paths. Tutorials require the tutorials option; if it is omitted, no tutorial pages are generated. Markdown tutorials are converted to HTML, and their identifier is the file name without its suffix. Tutorials can use link and tutorial inline tags, and a JSON file can supply titles and children.
The Markdown plugin converts Markdown in the default author, class description, description, parameter, property, returns, see and throws tags. Its default list does not include the example tag, which is shown as code anyway. Keep a leading asterisk on each comment line; configuration can add tags or remove defaults. For related language-level practices, see JavaScript docs testing and TypeScript docs testing.
Build an illustrative project
Install JSDoc for the sample project. The verification used JSDoc 4.0.5.
npm install --save-dev jsdoc
This manifest exposes the local package by name. Node’s package self-reference lets the examples require that name from inside the package when exports are configured.
{
"name": "acme-units",
"version": "1.0.0",
"type": "commonjs",
"exports": "./lib/units.js",
"scripts": {
"docs": "jsdoc -c jsdoc.json"
},
"devDependencies": {
"jsdoc": "^4.0.5"
}
}
The illustrative configuration reads lib/, enables the Markdown plugin, and selects a README and tutorial directory. It writes the generated reference to out/.
{
"source": { "include": ["lib"] },
"plugins": ["plugins/markdown"],
"opts": {
"destination": "out",
"readme": "README.md",
"tutorials": "tutorials"
}
}
The source has two examples. One puts an expected result in a comment directly above a call; the other has a caption and a trailing comment. Neither comment is an assertion merely because it appears in an example.
/**
* Unit conversions.
* @module acme-units
*/
/**
* Convert bytes to whole kibibytes, rounding down.
* @param {number} bytes - A byte count.
* @returns {number} The number of kibibytes.
* @example
* const { toKiB } = require("acme-units");
* // returns 1
* toKiB(1536);
*/
function toKiB(bytes) {
return Math.floor(bytes / 1024);
}
/**
* Format a byte count for people.
* @param {number} bytes - A byte count.
* @returns {string} The formatted size.
* @example <caption>Formatting a file size.</caption>
* const { formatSize } = require("acme-units");
* console.log(formatSize(1536)); // 1.5 KiB
*/
function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
return `${(bytes / 1024).toFixed(1)} KiB`;
}
module.exports = { toKiB, formatSize };
The tutorial is a Markdown page with a JavaScript fence. It has an explicit import, so it can be tested as a reader-facing unit once the package is available.
# Getting started
Convert a size and print it:
```js
const { toKiB, formatSize } = require("acme-units");
console.log(toKiB(4096));
console.log(formatSize(512));
```
The README supplies another Markdown example and becomes the front page in this configuration.
# acme-units
Small helpers for byte counts.
```js
const { formatSize } = require("acme-units");
console.log(formatSize(2048));
```
Build the reference with the configuration. In the verified build, the output contained the README front page, module page, tutorial page and source page. Both comment examples appeared as code and the second caption appeared above its example.
npx jsdoc -c jsdoc.json
The functions appeared as inner members of the module because the exported object itself was not documented. That presentation did not change the examples. If a member is missing entirely, inspect the source paths and patterns before concluding that the extraction script failed.
See what the scan can reach
The command below plans a scan. In the verified execution, the project had no top-level docs/ folder, so the plain-project root scope found two pages: the README and tutorial. Their two JavaScript blocks passed. The example tags in lib/units.js were never read.
docsalive scan .
Once the generated scan-docs/ directory exists, a root scan lists it as a third page in this project. That can be useful, but it also makes regeneration important: stale generated content can otherwise be scanned alongside current source. The CLI without execution only extracts and plans; see /docs/cli/ for the available run options.
| JSDoc item | What JSDoc does | What the engine does in 0.6.3 |
|---|---|---|
| Example tag in a source comment | Shows its text as code | Never reads the comment |
| Multiple examples and captions | Associates examples with a doclet and displays captions | Does not see them until they are copied to Markdown |
| Source include and patterns | Select files from which doclets are created | Does not use JSDoc configuration to select source comments |
| JSON doclet export | Prints doclets and exits | Can scan a Markdown page generated from that export |
| README | Can use it as the front page | Scans the root README |
| Tutorial Markdown | Converts it to a tutorial page when configured | Scans it under the root scope in this project |
| JavaScript fence | Displays it in a page | Runs it with Node; results and comments are not compared |
Make a scan-ready copy
The script below is illustrative. It reads the doclets produced by JSDoc, preserves a leading caption as prose, and writes each example as a JavaScript fence. For one specific convention—a returns comment directly above a one-line call ending in a semicolon—it writes an assertion in the generated copy.
This is a test transformation, not a JSDoc rule. Review both the original example and the generated page. The original remains the material a reader sees, while the assertion checks one stated expectation.
"""Copy JSDoc @example blocks into a Markdown page a docs scan can read.
Run `npx jsdoc -X -c jsdoc.json > doclets.json` first: -X prints JSDoc's own
doclets, so the examples are the ones JSDoc would publish.
A "// returns VALUE" comment directly above a one-line call becomes an
assertion, so the documented return value is checked when the block runs.
"""
import json
import re
import sys
from pathlib import Path
doclets = json.loads(Path(sys.argv[1]).read_text())
out = Path(sys.argv[2])
CAPTION = re.compile(r"^\s*<caption>(.*?)</caption>\s*\n?", re.S)
RETURNS = re.compile(r"^(\s*)//\s*returns\s+(.+?)\s*$")
def checked(code):
lines = code.split("\n")
result = []
i = 0
while i < len(lines):
m = RETURNS.match(lines[i])
nxt = lines[i + 1].strip() if i + 1 < len(lines) else ""
if m and nxt.endswith(";") and "\n" not in nxt and not nxt.startswith(("const ", "let ", "var ")):
expr = nxt[:-1]
result.append(f'{m.group(1)}require("node:assert").deepStrictEqual({expr}, {m.group(2)});')
i += 2
continue
result.append(lines[i])
i += 1
return "\n".join(result)
page = ["# API examples", ""]
count = 0
for d in doclets:
if d.get("undocumented") or not d.get("examples"):
continue
for example in d["examples"]:
m = CAPTION.match(example)
caption = m.group(1).strip() if m else ""
code = CAPTION.sub("", example, count=1)
page += [f"## {d['longname']}", ""]
if caption:
page += [caption, ""]
page += ["```js", checked(code), "```", ""]
count += 1
dest = out / "api" / "examples.md"
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text("\n".join(page))
print(f"wrote {dest} ({count} examples)")
Generate doclets using the same configuration as the reference, then generate the page and plan its scan. In the verified execution with --docs-dir scan-docs, the scope comprised the root README and generated API page. All three blocks passed.
npx jsdoc -X -c jsdoc.json > doclets.json
python3 tools/jsdoc_scan_copy.py doclets.json scan-docs
docsalive scan . --docs-dir scan-docs
The script reported two copied examples:
wrote scan-docs/api/examples.md (2 examples)
This is the illustrative page it produced. The first expected value is now part of an assertion. The trailing comment on the second example remains unchanged and is not checked.
# API examples
## module:acme-units~toKiB
```js
const { toKiB } = require("acme-units");
require("node:assert").deepStrictEqual(toKiB(1536), 1);
```
## module:acme-units~formatSize
Formatting a file size.
```js
const { formatSize } = require("acme-units");
console.log(formatSize(1536)); // 1.5 KiB
```
The script has deliberate limits. It rewrites only a returns comment directly above a one-line call ending in a semicolon, and the stated value must be a valid JavaScript expression. It does not check trailing comments such as the one on the formatting line. Examples that rely on names they never import can fail as depends-on-context or with a reference error.
It reads only what -X reports with the selected configuration. Files outside source.include, or files matching the exclusion pattern, will not be there. It does not read tutorials or the README; the scan covers those pages separately. It treats every example as JavaScript. Regenerate scan-docs in CI, and review the generated page when changing the convention or script.
Make the expected behavior testable
This change is broken on purpose. It changes rounding down to rounding to the nearest integer, so the illustrated call now yields two instead of one.
- return Math.floor(bytes / 1024);
+ return Math.round(bytes / 1024);
JSDoc still built successfully. The original example also ran without error as an ordinary JavaScript block: its result and comment were not compared. The generated assertion failed, and the scan classified that failure as a runtime error needing review. Node’s assertion message began:
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
2 !== 1
A runtime error is a prompt to investigate, not an automatic conclusion that the documentation is wrong. Here the function description says it rounds down, so the change and expectation conflict. In another case the API behavior may have intentionally changed and the example may need an update. Review the intended contract before deciding which side to change.
As writing advice, put a require or import line in every standalone example. An example without one may be understandable in a surrounding tutorial but fail in isolation because a name is missing. If it intentionally relies on earlier context, say so and test the sequence. Write expected results in a form a check can verify, such as an assertion, or show a call and explain the expected value in prose. Comments are never compared.
A scan that simply runs a call can still be valuable: it can reveal a missing import or an exception. It cannot establish that a successful call returned the intended value unless the example itself checks that value. Keep assertions focused on stable behavior, and avoid presenting a generated test setup as a prerequisite that the published page never gives readers.
Triage the findings
| Finding | Likely cause | What to do |
|---|---|---|
| An example is missing from the doclet export | Its file was outside the configured source paths or filtered by a pattern | Inspect source.include, the include pattern and underscore-prefixed paths |
| The reference builds but an example fails | Rendering did not run the example | Reproduce with the intended package and correct the code or API |
| A copied example reports an undefined name | It relies on context or an import absent from the example | Add the reader-facing import or document and test the prerequisite |
| An assertion fails | The stated value and current behavior differ | Compare both with the intended contract before changing either |
| A plain example passes after a behavior change | It has no assertion for the changed result | Add a meaningful check for the promised behavior |
| A generated page is stale | It was not regenerated after a source or configuration change | Rebuild doclets and regenerate it in CI |
Read the categories together with the evidence. In this project a runtime error came from an assertion the generated page added, so the first question is whether the stated value or the code is the intended contract. A failure in the README or tutorial is different: those pages are what readers copy directly, so a missing import or a changed function name there is a reader-facing problem even if the reference pages look fine. See findings for how a likely documentation bug differs from a result that needs review.
Two quieter outcomes deserve the same attention. A block that passes may simply have run without checking anything, which is what happened to the unchanged example after the rounding change. And an example that never reached the generated page, because its file sat outside the source selection, is not reported at all. Compare the number of examples the script wrote with the number you expect from the reference before reading the scan totals.
Put the checks in the workflow
Run the reference build and extraction on changes to comments, source selection or the public API. Run the generated examples against the package version under review, and keep the README and tutorial scan in scope. On release, check the artifact readers will actually install where practical; a checkout and a published artifact can expose different packaging problems.
A local hook can provide fast feedback, but a CI run remains useful because local hooks can be skipped or absent. The pre-commit guide describes that boundary. For a reference that combines source comments and separate pages, API reference docs testing covers the wider mapping problem.
Use this checklist with a change:
[ ] Confirm JSDoc source paths and file patterns include intended files.
[ ] Build the reference and inspect examples and captions.
[ ] Export doclets with the reference configuration.
[ ] Regenerate the scan-ready API examples in CI.
[ ] Give standalone examples their required imports.
[ ] Add assertions for stable results that must be verified.
[ ] Scan the README, tutorials and generated examples.
[ ] Review runtime errors and skipped blocks in context.
[ ] Check the package artifact intended for readers.
Writing JSDoc examples a check can verify
Most of the work happens in the comment itself, before any tool runs. A few habits make the extraction and the scan far more useful, and they are writing advice rather than JSDoc rules.
Start each example with the line that brings the API into scope. JSDoc renders whatever text follows the tag, so an example that begins with a bare call reads well in a reference page but cannot run on its own. The same line tells readers which module name to use, which matters when a package exposes several entry points.
State results in a form a machine can check. The returns-comment convention in this guide works because the script recognizes one narrow shape and rewrites it. If your project prefers another convention, adapt the script deliberately and keep the convention written down in the contributor guide, so authors know which comments are checked and which are ordinary prose. A comment at the end of a line, like the one on the formatting example, stays a comment.
Keep one idea per example and use captions to say what it shows. Several short examples under one doclet are easier to check and easier to fix than one long example that mixes setup, happy path and error handling. When an example must show an error, show the thrown error in prose or with an assertion that expects it, rather than leaving a failing call in the code.
Avoid hidden state. An example that only works after an earlier example in a tutorial has run belongs in the tutorial, where readers see the order, and it should still repeat its import, because each JavaScript block is run as its own file. In the reference, each example is copied on its own, so it should stand alone.
DocsAlive fits after extraction: it runs supported Markdown examples and helps sort failures for review. It does not read JSDoc comments, infer assertions from comments, or establish that every source file was included by JSDoc. Use the doclet export and your own assertions to make those boundaries visible. For a first look at an existing public repository, the health check runs the engine on up to 40 docs pages; plans and limits are on pricing.
The sources we checked
These sources were read on November 15, 2026. Engine behavior was checked against engine 0.6.3 on the same day.
| Source | What it covers |
|---|---|
| JSDoc example tag | Examples, multiple examples and captions |
| JSDoc configuration | Source paths, patterns and recursion |
| JSDoc command line | Explain, readme, tutorials and output options |
| JSDoc tutorials | Tutorial files, identifiers and relationships |
| JSDoc Markdown plugin | Default converted tags and configuration |
| Node packages | Package exports and self-reference |
FAQ
Does JSDoc execute example tags?
No. JSDoc displays their text as highlighted code. A successful build does not verify imports, calls or expected values in those examples.
What does DocsAlive scan in this project?
In engine 0.6.3 it does not detect JSDoc or read source comments. With no docs folder it scans from the repository root, including the README and tutorials. Once scan-docs exists, a root scan picks it up too. JavaScript runs with Node, but results and comments are never compared.
Why did a returns comment fail to catch a changed result?
A comment is not an assertion. The illustrative extraction script rewrites one narrow comment convention into an assertion in a generated page; other comments remain unchecked.
Why is a source file absent from the exported doclets?
Check the configured source paths and patterns. The defaults select certain JavaScript file suffixes and ignore files and folders beginning with an underscore. The export can contain only what JSDoc processes.
Can an example omit its import?
It can rely on surrounding context, but that context must be clear and tested. For a standalone example, including the require or import line makes the reader's starting point and the test boundary clearer.
Does the extraction script cover tutorials?
No. It reads example strings from the doclet export. Scan the README and tutorial Markdown separately, and regenerate the copied API examples in CI.




