This content originally appeared on DEV Community and was authored by TenE
In modern JavaScript development, clear inline documentation is essential. JSDoc provides a structured approach to annotating code which greatly improves maintainability and understanding. By using JSDoc comments (/** ... */
), we can describe each function’s purpose, inputs, and outputs. Below, we define common data types and document key functions (with @param
, @returns
, and @example
tags) so that developers can easily understand how the blog app works.
/**
* @typedef {Object} Post
* @property {string} id - Unique identifier of the post.
* @property {string} title - The title of the post.
* @property {string} content - Full content of the post.
* @property {string} author - The author of the post.
* @property {Date} createdAt - Timestamp of when the post was created.
* @property {boolean} published - Whether the post is published.
*/
/**
* @typedef {Object} Comment
* @property {string} id - Unique identifier of the comment.
* @property {string} postId - ID of the post this comment belongs to.
* @property {string} author - Author of the comment.
* @property {string} text - Content of the comment.
* @property {Date} createdAt - Timestamp of when the comment was created.
* @property {boolean} approved - Whether the comment is approved (moderated).
*/
/**
* @typedef {Object} User
* @property {string} id - Unique identifier of the user.
* @property {string} username - Username of the user.
* @property {string} email - Email address of the user.
* @property {Date} joinedAt - Date the user registered.
* @property {boolean} isAdmin - Whether the user has admin privileges.
*/
Using @typedef
for these complex data models (Post, Comment, User) helps make our documentation reusable and clear. Next, we outline some general JSDoc guidelines and then provide examples for each feature of the blog app:
- Use
@param {Type} name - description
to describe each function parameter, including its type and purpose. - Use
@returns {Type} description
to describe the function’s return value (or promise). - Include an
@example
section to illustrate how to call the function, which is especially helpful for async or complex operations. - Write clear, concise descriptions: document as you code and avoid overly verbose text.
With those principles in mind, here are JSDoc comments for key parts of the blog application:
Rendering Blog Posts
When displaying posts, we need functions like renderPosts(posts)
or renderPost(post)
. For example:
/**
* Renders an array of blog posts into an HTML container.
* @param {Post[]} posts - Array of post objects to render (each having title, content, etc.).
* @returns {HTMLElement} The container element containing all rendered posts.
* @example
* const posts = [
* { id: '1', title: 'First Post', content: 'Hello world!', author: 'Alice', createdAt: new Date(), published: true }
* ];
* const container = renderPosts(posts);
* document.body.appendChild(container);
*/
function renderPosts(posts) {
// ...
}
- The
@param {Post[]}
tag describes thatposts
is an array ofPost
objects. - The
@returns {HTMLElement}
indicates what the function outputs (a DOM element). - An
@example
shows how to callrenderPosts
with a sample post object. This ensures other developers know exactly what to pass in and what to expect back.
Handling Post Creation and Editing
We document functions for creating or updating posts. For instance:
/**
* Creates a new blog post.
* @param {Object} postData - The data for the new post.
* @param {string} postData.title - The title of the post.
* @param {string} postData.content - The content of the post.
* @param {string} postData.author - The author of the post.
* @returns {Promise<Post>} A promise that resolves to the created post object.
* @example
* createPost({ title: 'New Post', content: 'Hello!', author: 'Bob' })
* .then(newPost => console.log('Created post ID:', newPost.id));
*/
function createPost(postData) {
// ...
}
/**
* Updates an existing blog post by ID.
* @param {string} postId - ID of the post to update.
* @param {Object} updates - Fields to update (e.g., title, content).
* @returns {Promise<Post>} A promise that resolves to the updated post object.
* @example
* editPost('1', { title: 'Updated Title' })
* .then(updated => console.log('Post now has title:', updated.title));
*/
function editPost(postId, updates) {
// ...
}
- Each parameter is documented: the
postData
object’s fields (title
,content
, etc.) have their own@param
lines. JSDoc allows nested@param
(e.g.,postData.title
) for object properties. - The functions return a
Promise<Post>
since they likely involve asynchronous database calls; we document that with@returns {Promise<Post>}
. - Example calls show how to use the function and handle the returned promise, as recommended for clarity.
Managing Comments
For comment functionality, we include posting, deleting, and moderating comments:
/**
* Posts a new comment to a blog post.
* @param {string} postId - ID of the post to comment on.
* @param {Object} commentData - The data for the new comment.
* @param {string} commentData.author - Comment author's name or ID.
* @param {string} commentData.text - The comment text.
* @returns {Promise<Comment>} A promise resolving to the created comment object.
* @example
* addComment('1', { author: 'Charlie', text: 'Great post!' })
* .then(comment => console.log('Comment ID:', comment.id));
*/
function addComment(postId, commentData) {
// ...
}
/**
* Deletes a comment by its ID.
* @param {string} commentId - Unique identifier of the comment to delete.
* @returns {Promise<void>} A promise that resolves when the comment is deleted.
* @example
* deleteComment('42').then(() => console.log('Comment deleted'));
*/
function deleteComment(commentId) {
// ...
}
/**
* Approves or rejects a pending comment (for moderation).
* @param {string} commentId - ID of the comment to moderate.
* @param {boolean} isApproved - `true` to approve, `false` to reject.
* @returns {Promise<Comment>} A promise resolving to the updated comment object.
* @example
* moderateComment('42', true).then(updated => console.log('Comment approved:', updated.approved));
*/
function moderateComment(commentId, isApproved) {
// ...
}
- We document
addComment
’spostId
andcommentData
(with its properties) in detail. - The
deleteComment
function returnsPromise<void>
since it has no value on success, which we note in@returns
. - Including examples (e.g. calling
addComment
and chaining.then
) shows how to handle the promises. - This thorough documentation (parameters and return values) makes comment features easy to use and maintain.
User Authentication (Login/Logout/Register)
Authentication functions should also be documented clearly:
/**
* Registers a new user.
* @param {Object} userData - The new user's data.
* @param {string} userData.username - Desired username.
* @param {string} userData.email - User's email address.
* @param {string} userData.password - Plaintext password for the account.
* @returns {Promise<User>} A promise that resolves to the created user object.
* @example
* registerUser({ username: 'jdoe', email: 'jdoe@example.com', password: 's3cr3t' })
* .then(user => console.log('Registered user ID:', user.id));
*/
function registerUser(userData) {
// ...
}
/**
* Authenticates a user with a username and password.
* @param {string} username - The user's username.
* @param {string} password - The user's password.
* @returns {Promise<boolean>} A promise that resolves to `true` if credentials are valid.
* @example
* loginUser('jdoe', 's3cr3t').then(success => console.log('Login successful:', success));
*/
function loginUser(username, password) {
// ...
}
/**
* Logs out the current user (invalidates the session).
* @returns {void} Does not return a value; ends the user's session.
* @example
* logoutUser();
*/
function logoutUser() {
// ...
}
- Each function’s parameters (
userData
,username
,password
) are detailed with@param
. - The return type for async functions is noted (e.g.
Promise<User>
forregisterUser
,Promise<boolean>
forloginUser
). - For
logoutUser
, which may be synchronous or simply end the session, we use@returns {void}
to indicate nothing is returned. - Example usage clarifies how to call each function and what result to expect. This follows JSDoc best practices for describing even simple utility functions.
Admin Panel Features
Admins have extra capabilities such as publishing posts or moderating users:
/**
* Publishes a blog post (makes it visible to the public).
* @param {string} postId - ID of the post to publish.
* @returns {Promise<Post>} A promise resolving to the published post.
* @example
* publishPost('1').then(post => console.log('Published:', post.published));
*/
function publishPost(postId) {
// ...
}
/**
* Unpublishes a blog post (hides it from the public view).
* @param {string} postId - ID of the post to unpublish.
* @returns {Promise<Post>} A promise resolving to the unpublished post.
* @example
* unpublishPost('1').then(post => console.log('Published status:', post.published));
*/
function unpublishPost(postId) {
// ...
}
/**
* Deletes a blog post by its ID.
* @param {string} postId - ID of the post to delete.
* @returns {Promise<void>} A promise resolving when deletion completes.
* @example
* deletePost('1').then(() => console.log('Post deleted'));
*/
function deletePost(postId) {
// ...
}
/**
* Bans (deactivates) a user by their ID.
* @param {string} userId - ID of the user to ban.
* @returns {Promise<User>} A promise resolving to the updated user object.
* @example
* banUser('42').then(user => console.log('User banned:', user.isAdmin === false));
*/
function banUser(userId) {
// ...
}
- Admin functions like
publishPost
,deletePost
, andbanUser
are each documented with@param
for the IDs they require. - The return types are usually promises of an updated object (or
void
if no data is returned). - Examples show how an admin action might be called and what to do with the result.
- This makes the admin panel code self-explanatory and safe to modify.
Utility Functions
Finally, utility helpers (e.g. date formatting or text truncation) are documented in the same way:
/**
* Formats a JavaScript `Date` into a readable string.
* @param {Date} date - The date to format.
* @param {string} [locale] - Optional locale string (default is "en-US").
* @returns {string} The date formatted as a string.
* @example
* console.log(formatDate(new Date(), 'en-GB')); // e.g., "25/06/2025"
*/
function formatDate(date, locale = 'en-US') {
// ...
}
/**
* Truncates text to a maximum length, adding an ellipsis if needed.
* @param {string} text - The text to truncate.
* @param {number} maxLength - Maximum allowed length of the text.
* @returns {string} The truncated text (with “…” if it was too long).
* @example
* console.log(truncateText('Hello World', 5)); // "Hello…"
*/
function truncateText(text, maxLength) {
// ...
}
- The
formatDate
function’s parameters and return type are documented, including an optionallocale
parameter (shown with square brackets in the description). - The
truncateText
function similarly has its inputs and output clearly described. - Examples demonstrate expected behavior (e.g. how long strings are shortened).
- Overall, clear JSDoc comments like these make even small utilities self-documenting.
These JSDoc comments collectively ensure that every part of the blog application—posts, comments, user auth, admin actions, and utilities—is well-documented. By following JSDoc conventions (with @param
, @returns
, @example
, etc.) and writing clear descriptions, developers can easily read and maintain the codebase.
This content originally appeared on DEV Community and was authored by TenE

TenE | Sciencx (2025-06-27T09:40:28+00:00) Document Your JavaScript Code Like a Pro with JSDoc. Retrieved from https://www.scien.cx/2025/06/27/document-your-javascript-code-like-a-pro-with-jsdoc/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.