automadocs / guides / document-javascript-code.md
00
Guide
How to Document JavaScript Code
Master JSDoc, TypeScript declarations, and modern documentation tools for JavaScript projects.
01
JSDoc
JSDoc Basics
JSDoc is the standard way to document JavaScript. Modern IDEs like VS Code parse JSDoc to provide IntelliSense, type checking, and hover documentation.
Function Documentation
/**
* Calculate the total price with tax.
*
* @param {number} price - Base price before tax
* @param {number} [taxRate=0.1] - Tax rate as decimal
* @returns {number} Total price including tax
* @throws {Error} If price is negative
*
* @example
* calculateTotal(100, 0.08) // Returns 108
*/
function calculateTotal(price, taxRate = 0.1) {
if (price < 0) throw new Error("Price cannot be negative");
return price * (1 + taxRate);
}Class Documentation
/**
* Shopping cart for managing items.
*
* @class
* @example
* const cart = new ShoppingCart();
* cart.addItem({ name: "Widget", price: 9.99 });
*/
class ShoppingCart {
/**
* Create a new shopping cart.
* @param {Object} [options] - Cart configuration
* @param {string} [options.currency="USD"] - Currency code
*/
constructor(options = {}) {
/** @type {Array<Object>} */
this.items = [];
/** @type {string} */
this.currency = options.currency || "USD";
}
/**
* Add an item to the cart.
* @param {Object} item - Item to add
* @param {string} item.name - Item name
* @param {number} item.price - Item price
*/
addItem(item) {
this.items.push(item);
}
}02
Types
TypeScript-Style Types in JSDoc
You can use TypeScript syntax in JSDoc for complex types:
/**
* @typedef {Object} User
* @property {number} id - Unique identifier
* @property {string} name - Display name
* @property {string} email - Email address
* @property {"admin" | "user" | "guest"} role - User role
*/
/**
* Fetch user from API.
* @param {number} userId - User ID to fetch
* @returns {Promise<User | null>} User object or null
*/
async function getUser(userId) {
const response = await fetch(`/api/users/${userId}`);
return response.json();
}03
React
Documenting React Components
/**
* Button component with loading state.
*
* @param {Object} props - Component props
* @param {React.ReactNode} props.children - Button content
* @param {boolean} [props.loading=false] - Show loading spinner
* @param {"primary" | "secondary"} [props.variant="primary"] - Button style
* @param {() => void} [props.onClick] - Click handler
* @returns {JSX.Element} Rendered button
*
* @example
* <Button variant="primary" onClick={handleSubmit}>
* Submit
* </Button>
*/
function Button({ children, loading = false, variant = "primary", onClick }) {
return (
<button className={variant} onClick={onClick} disabled={loading}>
{loading ? <Spinner /> : children}
</button>
);
}04
Tools
Documentation Generation Tools
JSDoc
Official JSDoc generator. Creates HTML documentation from comments.
npm install -g jsdocTypeDoc
Documentation generator for TypeScript projects.
npm install typedocStorybook
Interactive component documentation for React, Vue, Angular.
npx storybook init05
Practices
Best Practices
- Document exports - Focus on public APIs that others will use
- Add examples - Show usage, not just parameter lists
- Use @typedef for complex types - Define reusable type definitions
- Enable VS Code JSDoc checking - Add
"checkJs": trueto jsconfig.json - Consider TypeScript - Types serve as living documentation
06
Generate
Generate Types from JSDoc
TypeScript can generate .d.ts files from JSDoc comments:
// tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "types"
},
"include": ["src/**/*.js"]
}Run tsc to generate type definitions that npm packages can include.
08
Start
Try AutomaDocs Free
Connect your JavaScript or TypeScript repository and publish docs in about a minute. New commits trigger updates so pages stay current.