JSDoc: The ultimate guide to documenting your JavaScript code
Take a deep dive into JSDoc and uncover how this powerful tool can transform the way you write and document your JavaScript code.
Have you ever been working on some JavaScript code and come across the @param annotation? Did you stop and wonder, "what does this even mean?" If so, you're in luck! In this blog post, we're going to dive deep into the world of JSDoc and explore how it can help you document your code like a pro.
No more confusion over those mysterious annotations! So, let's get started and uncover the benefits of JSDoc for JavaScript developers.
As a JavaScript developer, you have likely come across code snippets that include annotations such as @param
, @return
, or @throws
. For example,
These annotations are a part of JSDoc, a tool that helps developers concisely and clearly document their code. You may use JSDoc to offer useful details about the behaviour and implementation of your code, making it simpler for others to understand and use.
Whether you are new to JavaScript or a seasoned developer, you will learn how to use JSDoc to write better, more maintainable code.
Now let's go into the realm of JSDoc and begin confidently documenting code!
what is JSDocs? π€
JSDoc is a tool for creating documentation from JavaScript source code. It uses special comments, written in a specific format, to describe the code and its behaviour. The tool then turns these comments into human-readable documentation, making it simpler for others to understand the code and know how to utilise it.
Whether you are working on a small side project or a large-scale enterprise application, JSDoc can help you keep your code well-documented and easily accessible to others.
Here is a simple example of how JSDoc can be used in JavaScript code:
/**
* Adds two numbers together.
*
* @param {number} num1 - The first number to add.
* @param {number} num2 - The second number to add.
* @returns {number} The sum of the two numbers.
*/
function addNumbers(num1, num2) {
return num1 + num2;
}
The JSDoc comments in this example define the purpose of the addNumbers
function, its parameters, and its return value. When the JSDoc tool is used on this code, it will create documentation that clearly describes what the addNumbers
method does and how to use it.
installation β¬οΈ
Use this command to install JSDoc globally with npm.
npm install -g jsdoc
Instead, run the following command to set it up for only one project:
npm install --save-dev jsdoc
Installing this package is not necessary until you need to use JSDoc to create the documentation webpage.
Instead, VSCode can be utilized with it.
built-in support in VSCode π©βπ»
Visual Studio Code (VSCode) has built-in support for JSDoc, making it easier for us to document your code. Here are some of the features VSCode provides for JSDoc:
IntelliSense: VSCode provides IntelliSense for JSDoc tags and syntax, which helps you write JSDoc comments more efficiently and with fewer errors.
Before the function declaration, type
/**
and press enter to see the generated snippet.Hover Preview: VSCode displays a preview of the JSDoc comments when you hover over a symbol in your code. This makes it easier to see the documentation for a symbol without having to navigate to its definition.
Signature Help: VSCode displays signature information for functions and methods in the JSDoc comments. This makes it easier to understand the purpose and expected parameters of a function or method.
Error Checking: VSCode checks your JSDoc comments for errors and provides warnings and suggestions for improvement.
By using these features, VSCode can help you write high-quality JSDoc documentation for your JavaScript code. Additionally, VSCode integrates with JSDoc to allow you to generate a website or API documentation from your JSDoc comments.
tags in JSDocs π
Here is a list of some of the most commonly used JSDoc tags to document your JavaScript code:
@param
: Describes a parameter for a function or method.@returns
: Describes the return value of a function or method.@throws
: Describes an error that may be thrown by a function or method./** * Parses a string as a number. * @function * @param {string} str - The string to parse. * @throws {TypeError} If the string is not a valid number. * @returns {number} The parsed number. */ function parseNumber(str) { let num = Number(str); if (isNaN(num)) { throw new TypeError(`"${str}" is not a valid number`); } return num; }
@type
: Specifies the type of a variable or property./** * An object representing a point in 2D space. * @typedef {Object} Point * @property {number} x - The x-coordinate of the point. * @property {number} y - The y-coordinate of the point. */ /** * Gets the distance between two points. * @function * @param {Point} a - The first point. * @param {Point} b - The second point. * @returns {number} The distance between the two points. */ function getDistanceBetweenPoints(a, b) { let dx = b.x - a.x; let dy = b.y - a.y; return Math.sqrt(dx * dx + dy * dy); }
@typedef
: Defines a custom type for use in JSDoc documentation./** * A rectangle defined by its top-left corner and dimensions. * @typedef {Object} Rectangle * @property {number} x - The x-coordinate of the top-left corner. * @property {number} y - The y-coordinate of the top-left corner. * @property {number} width - The width of the rectangle. * @property {number} height - The height of the rectangle. */ /** * Gets the area of a rectangle. * @function * @param {Rectangle} rect - The rectangle. * @returns {number} The area of the rectangle. */ function getRectangleArea(rect) { return rect.width * rect.height; }
@callback
: Describes a callback function used as a parameter./** * @callback getProductsCallback * @param {Array} products - An array of products * @param {string|null} error - An error message, or null if there is no error */ /** * Get all products * @param {getProductsCallback} callback - A function to call when the products are retrieved */ function getProducts(callback) { // Logic to retrieve products from the server const products = [...]; const error = null; callback(products, error); }
@enum
: Describes an enumerated type./** * Enumeration of order statuses * @readonly * @enum {string} */ const OrderStatus = { PENDING: 'Pending', CONFIRMED: 'Confirmed', SHIPPED: 'Shipped', DELIVERED: 'Delivered', CANCELLED: 'Cancelled' }; // Example usage const currentStatus = OrderStatus.CONFIRMED; console.log(`Current status: ${currentStatus}`); // Output: Current status: Confirmed
@see
: Provides a reference to another related piece of documentation./** * Calculates the sum of two numbers. * * @param {number} a - The first number. * @param {number} b - The second number. * @returns {number} The sum of a and b. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sum MDN} */ function add(a, b) { return a + b; }
@example
: Provides an example of how to use a function or method./** * Calculates the total price of an order * @param {Array} items - An array of order items * @example * const orderItems = [ * { name: 'Product 1', price: 10.99, quantity: 2 }, * { name: 'Product 2', price: 5.99, quantity: 3 } * ]; * const totalPrice = calculateOrderTotal(orderItems); * console.log(`Total price: ${totalPrice}`); // Output: Total price: 39.95 */ function calculateOrderTotal(items) { let total = 0; for (const item of items) { total += item.price * item.quantity; } return total; }
@author
: Specifies the author of a piece of code./** * Calculates the factorial of a number. * * @param {number} num - The number to calculate the factorial of. * @returns {number} The factorial of num. * * @author * Prerana Nawar <precodes@example.com> */ function factorial(num) { if (num <= 1) { return 1; } return num * factorial(num - 1); }
@since
: Specifies the version of the code that introduced a piece of code./** * Calculates the power of a number. * * @param {number} base - The base number. * @param {number} exponent - The exponent to raise the base to. * @returns {number} The result of raising the base to the exponent. * * @since 1.2.0 */ function power(base, exponent) { return Math.pow(base, exponent); }
@deprecated
: Indicates that a piece of code is no longer recommended for use and will be removed in the future./** * @deprecated Use the `calculateTotalWithDiscount` function instead. */ function calculateTotal(subtotal, discountPercent) { // Calculate total using subtotal and discount percent } /** * Calculates the total with discount applied. * * @param {number} subtotal The subtotal of the items. * @param {number} discountPercent The discount percentage to apply. * @returns {number} The total with discount applied. */ function calculateTotalWithDiscount(subtotal, discountPercent) { // Calculate total with discount applied }
These tags can be used in combination with each other and with text to provide a comprehensive description of your code and how it works.
/**
* Makes an API call to fetch information about a user.
* @function
* @param {string} userId - The ID of the user to fetch information for.
* @param {Object} [options={}] - An optional object containing request options.
* @param {string} [options.token] - An optional authentication token.
* @param {string} [options.language='en'] - The language to retrieve the information in.
* @returns {Promise} A promise that resolves with the user information or rejects with an error.
*/
async function getUserInformation(userId, options = {}) {
let { token, language = 'en' } = options;
try {
let response = await fetch(`https://api.example.com/users/${userId}`, {
headers: {
Authorization: token ? `Bearer ${token}` : undefined,
'Accept-Language': language
}
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
let data = await response.json();
return data;
} catch (error) {
console.error(error);
throw error;
}
}
By using JSDoc tags to document your code, you can make it easier for others to understand and use, and you can also make it easier for yourself to understand your code if you come back to it later.
tips and tricks π₯
Here are some tips and tricks for using JSDoc to document your JavaScript code:
Use Templates: JSDoc supports templates that allow you to format your documentation in a specific way. You can use the default template or create your own custom template to match your project's style.
Use Markdown: JSDoc supports Markdown syntax within its comments, which allows you to add formatting, links, and images to your documentation.
Use @alias: The
@alias
tag allows you to create an alias for a symbol. This is useful when you have a long or complex symbol name that you want to simplify.Use @tutorial: The
@tutorial
tag allows you to link to a tutorial from within your documentation. This is useful for providing additional information about a symbol or group of symbols.Use the
@link
tag to provide links to other documentation: By using@link
, you can include links to other relevant documentation within your JSDoc comments.Use the
@inheritdoc
tag to inherit JSDoc comments from a parent class or function: By using@inheritdoc
, you can simplify your JSDoc documentation by inheriting comments from a parent class or function.
By using these tips and tricks, you can enhance the quality and readability of your JSDoc documentation.
I hope you learned how to utilise JSDoc to produce better, more readable code, regardless of your level of JavaScript experience.
In conclusion, JSDoc is not just a bunch of annotations, it's a powerful tool that can take your JavaScript development to the next level. By providing clear and concise documentation for your code, you can save yourself and your fellow developers countless hours of confusion and frustration. So next time you're writing JavaScript, don't forget to include some JSDoc comments - your future self will thank you!
And remember, when it comes to coding, the only thing worse than no documentation is deprecated documentation. So keep your JSDoc up to date and happy coding!