Introduction to JSDoc
JSDoc is a documentation syntax that uses specially formatted comments to describe JavaScript code. Developers use it to document functions, parameters, return values, classes, properties, and other parts of an application. These comments make code easier to understand and help development tools provide useful information while writing and maintaining software.
TypeScript understands many JSDoc annotations. In JavaScript files, developers can use JSDoc to describe types without converting the implementation to TypeScript. When JavaScript checking is enabled, TypeScript can use those annotations to identify certain type errors and improve editor suggestions.
JSDoc is also useful inside TypeScript files. Although TypeScript already supports native type annotations, JSDoc comments can explain the purpose of a function, describe parameters in more detail, show examples, mark deprecated APIs, and communicate behavior that a type signature alone cannot fully express.
Understanding JSDoc helps developers maintain mixed JavaScript and TypeScript projects, document public APIs, and make reusable code easier for other developers to consume.
1. Writing Your First JSDoc Comment
A JSDoc comment begins with /** and ends with */. It is commonly placed immediately before the function, class, or declaration it describes. Tags beginning with @ provide structured information such as parameter types and return types.
/**
* Greets a user by name.
* @param {string} name - The user's name.
* @returns {string} A greeting message.
*/
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Asha"));
The first line describes what the function does. The @param tag documents the name and expected type of the input parameter, while @returns describes the type and meaning of the returned value.
This example is valid JavaScript because the type information appears inside comments rather than as TypeScript-specific syntax. Editors and TypeScript can use these annotations to provide better documentation and static analysis when the relevant tooling is enabled.
JSDoc comments are not runtime validation. Calling this function with an unexpected value does not automatically cause JavaScript to enforce the documented string type.
2. Documenting Function Parameters with @param
The @param tag describes a function parameter. In JavaScript files, including a type in braces allows TypeScript-aware tools to understand the expected type when checking the implementation or its callers.
/**
* Calculates the total price of a product.
*
* @param {number} price - Price of one item.
* @param {number} quantity - Number of items.
* @returns {number} The calculated total.
*/
function calculateTotal(price, quantity) {
return price * quantity;
}
console.log(calculateTotal(250, 3));
Each @param entry describes one parameter. Include the type, the parameter name, and a meaningful explanation when that information helps callers understand how the function should be used.
When TypeScript checks this JavaScript file, the JSDoc types can help it identify invalid calls, such as passing a string where a number is expected. To report such errors in JavaScript files, enable JavaScript checking in the project configuration or use compatible editor checking.
Good parameter descriptions explain more than the data type. For example, document whether a quantity must be positive, whether a date represents UTC, or whether an argument is a unique identifier when those conditions matter to the API.
3. Documenting Return Values with @returns
The @returns tag documents the value a function produces. It can describe the return type as well as explain what the caller should expect from the result.
/**
* Converts a value from Celsius to Fahrenheit.
*
* @param {number} celsius - Temperature in Celsius.
* @returns {number} Temperature in Fahrenheit.
*/
function toFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
console.log(toFahrenheit(25));
The return annotation communicates that the function produces a number. The description clarifies the unit of the result, which is useful because the type alone cannot distinguish Celsius from Fahrenheit.
For functions that do not return a meaningful value, you may document the return behavior without inventing a result type. In TypeScript-aware JSDoc, @returns {void} can explicitly describe a function whose return type is void.
Document special return behavior when needed. If a function can return undefined, null, an empty collection, or a sentinel value, explain the circumstances so callers can handle the result appropriately.
4. Documenting Optional Parameters
Some functions allow callers to omit an argument. JSDoc supports optional parameter notation using square brackets around the parameter name. When describing JavaScript, the documentation should match how the function actually behaves when the argument is missing.
/**
* Creates a greeting for a user.
*
* @param {string} name - The user's name.
* @param {string} [title] - An optional title.
* @returns {string} The completed greeting.
*/
function createGreeting(name, title) {
if (title) {
return "Hello, " + title + " " + name + "!";
}
return "Hello, " + name + "!";
}
console.log(createGreeting("Asha"));
console.log(createGreeting("Asha", "Dr."));
The square brackets indicate that title may be omitted. The function checks whether a title was supplied before including it in the greeting.
Another convention allows documenting a parameter with a default value, such as @param {number} [limit=10]. This communicates the intended default to readers and compatible tools, but the implementation must still actually apply that default.
Do not document a parameter as optional when callers are required to provide it. Incorrect documentation creates confusion and can make the editor's displayed function signature misleading.
5. Using @typedef to Define Custom Types
The @typedef tag creates a named type definition in JSDoc. It is useful when several functions work with the same object structure and you want to avoid repeatedly describing every property.
/**
* Represents a course.
*
* @typedef {Object} Course
* @property {number} id - Unique course identifier.
* @property {string} title - Course title.
* @property {boolean} published - Publication status.
*/
/**
* Returns the title of a course.
*
* @param {Course} course - The course record.
* @returns {string} The course title.
*/
function getCourseTitle(course) {
return course.title;
}
const course = {
id: 101,
title: "TypeScript Fundamentals",
published: true
};
console.log(getCourseTitle(course));
The Course typedef describes an object with three properties. The function can then refer to Course in its parameter documentation instead of repeating the entire object structure.
Reusing named definitions improves consistency when multiple functions operate on the same data model. It also makes code easier to navigate because developers can find the documented structure in one place.
For larger projects, avoid maintaining duplicate descriptions of the same domain model across many JSDoc comments. When a model has complex constraints or is shared extensively, a TypeScript interface or type alias may be a better long-term choice.
6. Documenting Union Types
A union type represents a value that can belong to one of several types. In JSDoc, the pipe character can describe a union, allowing TypeScript-aware tools to understand that a function accepts or returns multiple possible types.
/**
* Converts a string or number into a string.
*
* @param {string | number} value - The value to convert.
* @returns {string} The converted string.
*/
function convertToString(value) {
return String(value);
}
console.log(convertToString(101));
console.log(convertToString("TypeScript"));
The parameter accepts either a string or a number. Both inputs are supported by the String() conversion, so the implementation can safely produce a string for either case.
You can also document a union of more specific values, such as @param {"success" | "error"} status. This is useful when an API supports only a known set of strings rather than arbitrary text.
Be careful not to document a broader input type than the function can actually handle. JSDoc should describe the real implementation, rather than merely expressing what would be convenient for callers.
7. Documenting Arrays and Collections
JSDoc can describe arrays of values using forms such as number[] or Array<string>. For arrays containing objects, a named typedef can make the expected element structure easier to understand.
/**
* @typedef {Object} Course
* @property {number} id
* @property {string} title
*/
/**
* Finds a course by its identifier.
*
* @param {Course[]} courses - Available courses.
* @param {number} id - Identifier to find.
* @returns {Course | undefined} The matching course, if found.
*/
function findCourseById(courses, id) {
return courses.find(course => course.id === id);
}
const courses = [
{ id: 1, title: "HTML" },
{ id: 2, title: "TypeScript" }
];
const course = findCourseById(courses, 2);
if (course) {
console.log(course.title);
}
Course[] describes an array of Course objects. The return annotation includes undefined because Array.find() returns undefined when no matching element is found.
This is an important distinction: documenting a return value as Course alone would imply that a course is always found, which does not match the function's actual behavior.
Correct array and collection annotations help callers understand element types, available properties, and cases where a lookup may fail.
8. Documenting Generic Functions with @template
JSDoc supports the @template tag for describing generic type parameters. This allows JavaScript functions to preserve relationships between inputs and outputs without using TypeScript-specific syntax in the implementation file.
/**
* Returns the supplied value.
*
* @template T
* @param {T} value - The value to return.
* @returns {T} The original value.
*/
function identity(value) {
return value;
}
const courseName = identity("TypeScript");
const courseId = identity(101);
console.log(courseName);
console.log(courseId);
The @template T tag introduces a generic type parameter. Both the function parameter and return annotation refer to T, preserving the relationship between the input and output.
When TypeScript analyzes this JavaScript file, it can infer T from the supplied value. This makes JSDoc useful for maintaining reusable, type-aware JavaScript utilities.
Generic JSDoc functions are particularly useful during gradual migrations. Teams can introduce generic type relationships and better editor support without immediately rewriting every function as TypeScript.
9. Documenting Callback Functions
A callback is a function passed into another function for execution later or as part of a particular operation. JSDoc can define callback signatures using @callback, making complex function parameters easier to document and reuse.
/**
* Transforms a numeric value.
*
* @callback NumberFormatter
* @param {number} value - The number to format.
* @returns {string} The formatted value.
*/
/**
* Applies a formatter to a number.
*
* @param {number} value - The original number.
* @param {NumberFormatter} formatter - Formatting function.
* @returns {string} The formatted number.
*/
function formatNumber(value, formatter) {
return formatter(value);
}
const formatted = formatNumber(
1234,
value => value.toFixed(2)
);
console.log(formatted);
NumberFormatter describes a function that receives a number and returns a string. The main function uses that named callback type rather than repeating the full function signature.
Named callback documentation is especially helpful for event handlers, transformation functions, sorting callbacks, validation handlers, and APIs that accept several callbacks.
Keep the documented callback signature consistent with how the function is actually invoked. If the implementation passes additional arguments or expects asynchronous results, those behaviors should be documented accurately.
10. Documenting Classes and Properties
JSDoc can describe classes, constructors, instance properties, and methods. Clear class documentation is useful when other developers need to understand how an object should be created and used.
/**
* Represents a course available on the platform.
*/
class Course {
/**
* Creates a course.
*
* @param {number} id - Unique course identifier.
* @param {string} title - Course title.
*/
constructor(id, title) {
/** @type {number} */
this.id = id;
/** @type {string} */
this.title = title;
}
/**
* Returns the course's display name.
*
* @returns {string} The course title.
*/
getTitle() {
return this.title;
}
}
const course = new Course(101, "TypeScript");
console.log(course.getTitle());
The class-level comment explains the purpose of Course. Constructor annotations document the values needed to create an instance, and property annotations describe the expected types of instance fields.
The getTitle method has its own description and return type. IDEs can use this information to display helpful documentation when developers inspect or call the method.
JSDoc is particularly valuable for JavaScript classes when a project enables checkJs and wants to improve type checking without converting the entire class to TypeScript. The annotations still need to match the actual object behavior.
11. Useful JSDoc Tags for Real Projects
Beyond parameter and return annotations, JSDoc provides tags that help teams communicate how code should be used, what assumptions it makes, and which APIs may change in the future.
| Tag | Purpose |
|---|---|
| @param | Documents a function parameter and its expected type. |
| @returns | Describes the return value. |
| @typedef | Defines a reusable named type description. |
| @property | Documents properties of a described object type. |
| @template | Introduces generic type parameters. |
| @callback | Defines a reusable callback signature. |
| @example | Provides an example of how to use an API. |
| @deprecated | Marks an API as deprecated and can explain its replacement. |
| @throws | Documents an error or exception the function may throw. |
/**
* Calculates a discount-adjusted price.
*
* @param {number} price - Original price.
* @param {number} discount - Discount percentage from 0 to 100.
* @returns {number} Price after applying the discount.
* @throws {RangeError} If the discount is outside its valid range.
* @example
* calculateDiscount(100, 20); // Returns 80
*/
function calculateDiscount(price, discount) {
if (discount < 0 || discount > 100) {
throw new RangeError("Discount must be from 0 to 100.");
}
return price - (price * discount) / 100;
}
console.log(calculateDiscount(100, 20));
These tags communicate both the intended types and the function's behavior. The @throws documentation is especially useful because the type signature does not explain when the function rejects an input by throwing an exception.
12. JSDoc in JavaScript vs TypeScript
JSDoc and TypeScript annotations can complement each other, but they serve somewhat different purposes. JavaScript can use JSDoc comments to describe types without introducing TypeScript-specific syntax. TypeScript files can use native annotations for static types while still benefiting from JSDoc descriptions.
// JavaScript with JSDoc
/**
* @param {number} first
* @param {number} second
* @returns {number}
*/
function add(first, second) {
return first + second;
}
// TypeScript with native annotations
/**
* Adds two numeric values.
*/
function add(first: number, second: number): number {
return first + second;
}
In the JavaScript version, the expected types are described inside comments. In the TypeScript version, the compiler checks the parameter and return types through native syntax, while the comment explains the function's purpose.
Use JSDoc type annotations when maintaining JavaScript that benefits from stronger tooling, when documenting external JavaScript APIs, or when gradually migrating a codebase. In a TypeScript file, native types are usually the clearest way to declare ordinary parameter and return types.
JSDoc is not a replacement for TypeScript's entire type system. Some TypeScript features and type expressions cannot be expressed in JSDoc in exactly the same way, so complex type designs may be easier to maintain using native TypeScript declarations.
13. Common JSDoc Mistakes
Using incorrect parameter types
If a comment documents a number but the implementation expects a string, the documentation and static analysis become misleading. Keep annotations aligned with the actual function behavior.
Forgetting possible undefined results
A lookup function may not find a match. Document the return type as including undefined when that possibility exists instead of implying success is guaranteed.
Writing comments without useful explanations
Repeating the function name adds little value. Explain important assumptions, units, side effects, constraints, or reasons a caller should choose one option over another.
Expecting JSDoc to validate runtime values
JSDoc annotations do not automatically insert runtime checks. Validate untrusted input explicitly when the application depends on its actual structure or values.
Documenting the same type repeatedly
When several functions share a complex object structure, consider a reusable typedef or a TypeScript interface instead of maintaining many duplicated type descriptions.
Best Practices for JSDoc
- Write JSDoc for public functions, reusable utilities, exported classes, and non-obvious behavior.
- Use @param and @returns to describe the intended contract of JavaScript functions.
- Use @typedef and @property to document reusable object structures.
- Use @template for generic JavaScript functions when the relationship between inputs and outputs matters.
- Describe optional parameters, possible missing results, side effects, and exceptions accurately.
- Enable checkJs when you want TypeScript to check JavaScript files using available type information.
- Use native TypeScript types for ordinary type declarations in TypeScript files.
- Keep comments focused on meaningful behavior rather than repeating obvious implementation details.
- Validate untrusted runtime data even when its expected shape is described using JSDoc.
Conclusion
JSDoc is a practical way to document JavaScript code and provide additional type information that tools such as TypeScript can understand. Its tags support parameters, return values, custom types, arrays, callbacks, generic functions, classes, examples, and deprecated APIs.
Use JSDoc to make JavaScript modules easier to understand, improve editor assistance, and support gradual TypeScript adoption. Combine accurate annotations with appropriate checking, testing, and runtime validation to create code that is both easier to maintain and safer to use.