The Art of Comments
Write code that documents itself. Master CSS and JavaScript commenting techniques that enhance team collaboration, preserve institutional knowledge, and improve long-term maintainability.
Comments are the bridge between what code does today and what a developer needs to understand tomorrow. In the fast-paced world of web development, where projects evolve rapidly and teams change frequently, well-crafted comments serve as essential documentation that keeps codebases maintainable and teams productive.
Modern web development with Next.js has fundamentally changed how we think about code organization and documentation. The framework's emphasis on server components, React Server Components, and performance optimization means that understanding the "why" behind code decisions is just as important as understanding the "what." Comments help future developers--including yourself--navigate complex architectural choices, understand performance implications, and make informed decisions when extending functionality. For more on structuring Next.js projects effectively, see our guide on Next.js Project Structure Best Practices.
The art of commenting lies not in explaining every line of code, but in providing context that cannot be derived from the code itself. As noted by JavaScript.info, the key principle is that "if the code is so unclear that it requires a comment, then maybe it should be rewritten instead." This philosophy guides effective commenting practices: comments should explain the reasoning behind non-obvious decisions, document known issues and their workarounds, and provide guidance for future maintainers.
Why Comments Matter in Modern Web Development
Team Communication
CSS and JavaScript comments explain not just what code does, but why certain decisions were made--essential for multi-developer projects.
Long-term Maintainability
Code is read far more often than it's written. Comments save hours of debugging when returning to code months or years later.
Inline Documentation
Comments travel with your code, always synchronized with what they describe--unlike external documentation that can drift out of sync.
CSS Commenting Fundamentals
CSS comments use a specific syntax that distinguishes them from other types of documentation. Unlike JavaScript, which supports multiple comment styles, CSS relies exclusively on the /* */ syntax for both single-line and multi-line comments. This consistency makes CSS comments immediately recognizable to developers working across stylesheets.
The opening delimiter /* marks the beginning of a comment, while */ signals its end. Everything between these markers--including line breaks, whitespace, and nested markers--is treated as comment text and ignored by the browser's CSS parser. This means CSS comments cannot be nested within each other; attempting to nest comments will cause parsing errors where the first */ encountered will close the comment prematurely, as documented in MDN CSS Comments.
Single-line comments in CSS are achieved by wrapping the text within /* and */, even when the comment occupies just one line. While some developers prefer multi-line formats for any comment longer than a few words, consistency matters more than personal preference. Establish team conventions for comment length and format, then apply them uniformly across the stylesheet.
1/* This is a single-line comment */2 3/*4 * This is a multi-line comment5 * that spans several lines6 */Strategic CSS Documentation Approaches
Documenting CSS requires a different mindset than commenting in programming languages like JavaScript. CSS is inherently descriptive--it describes how elements should appear--yet the decisions behind those descriptions often require explanation. When documenting stylesheets, focus on explaining the reasoning behind design choices, not the syntax itself, as covered in the Zero to Mastery CSS comments guide.
Effective CSS comments often address questions that arise during maintenance: Why was this specific approach chosen? What alternatives were considered and rejected? How does this style interact with other parts of the system? These questions reveal the architectural thinking that raw CSS cannot express. For a deeper dive into scalable CSS architecture, see our guide on CSS Architecture for Large Projects.
Documentation frameworks like SassDoc, KSS, and MDCSS provide structured approaches to CSS documentation. SassDoc is particularly popular in modern Next.js projects using Sass preprocessing, as it parses special comment annotations to generate API documentation automatically. These tools encourage developers to document functions, mixins, and variables consistently, creating living documentation that stays current with the codebase, as noted in Frank M Taylor's guide.
1/*2 * Responsive Grid System3 * Base: 4-column grid with 24px gutter4 * Breakpoints align with design system:5 * - Mobile: Single column, 16px padding6 * - Tablet: 2 columns, 24px padding7 * - Desktop: 4 columns, 32px padding8 */9.grid {10 display: grid;11 grid-template-columns: repeat(4, 1fr);12 gap: 24px;13 padding: 0 16px;14}JavaScript Commenting Best Practices
JavaScript supports two comment syntaxes, each serving distinct purposes. Single-line comments using // are ideal for brief annotations that fit on one line, while multi-line comments using /* */ accommodate longer explanations or temporary code disabling. Understanding when to use each type is fundamental to writing readable JavaScript.
Single-line comments are the most commonly used style in modern JavaScript. They work well for inline annotations, quick explanations, and TODO markers. The comment continues until the end of the line, making them concise and non-intrusive. However, resist the temptation to use single-line comments for explanations that would be clearer as prose--multi-line comments exist precisely for this purpose, as explained in JavaScript.info.
Multi-line comments excel at providing detailed explanations, documenting function behavior, and temporarily disabling blocks of code. In Next.js applications, multi-line comments often document API integrations, explain complex algorithmic choices, and provide context for non-obvious implementation decisions.
// Single-line comment for quick notes const increment = (n) => n + 1; // TODO: Refactor this for better performance // This function processes large arrays
Documentation Comments with JSDoc
JSDoc transforms comments into structured documentation that tools can parse and present as API references. By following JSDoc conventions, developers create living documentation that describes function signatures, parameter types, return values, and more. This is especially valuable in Next.js projects where functions accept props, handle API requests, and interact with external services.
A typical JSDoc comment block begins with /** and uses tags like @param, @returns, and @example to describe function behavior. TypeScript projects often use TSDoc, which extends JSDoc with additional tags for TypeScript-specific features. Both conventions share the same core philosophy: document the interface, not the implementation. For more on TypeScript best practices including type documentation, see our TypeScript Best Practices for Enterprise Apps guide.
1/**2 * Calculates the optimal cache duration for a given route.3 * @param {string} route - The API route path4 * @param {number} trafficLevel - Estimated traffic volume (1-10)5 * @returns {number} Cache duration in seconds6 * @example7 * getCacheDuration('/api/users', 5)8 * // Returns: 609 */10export function getCacheDuration(route, trafficLevel) {11 // Implementation...12}Comment Types and Their Purposes
Comments serve different purposes. Understanding these categories helps you apply the right type of documentation in the right situation. As noted in Frank M Taylor's guide, maintenance comments acknowledge that code exists in various states of quality and completeness.
Maintenance Comments for Code Evolution
1// TODO (ticket: WEB-1234): Add ARIA labels for WCAG 2.1 compliance2// This is a temporary workaround for the legacy API limitation3// FIXME: This causes jank on mobile Safari (iOS 15-16)4// eslint-disable-next-line @typescript-eslint/no-explicit-anyPraxis Comments for API Documentation
Praxis comments--derived from the Greek word for practice--document the public interface of code components. These comments target consumers of your code rather than future maintainers, explaining what a function does, how to use it, and what to expect from it. JSDoc, TSDoc, and SassDoc are all examples of praxis comment systems, as explained in Frank M Taylor's guide.
Praxis comments should answer the questions a developer would have when encountering your code for the first time: What does this do? What parameters does it accept? What does it return? Are there any side effects? What exceptions might it throw? By providing complete answers to these questions, praxis comments enable developers to use code correctly without reading implementation details.
The key principle guiding praxis comments is documenting the contract, not the implementation. A function's praxis comments should describe behavior at the level of its public interface. Implementation details that don't affect external behavior belong in maintenance comments or inline explanations, not in praxis documentation.
Avoiding Common Commenting Pitfalls
The Problem with Explanatory Comments
// BAD: States the obvious counter++; // Increment counter by one
Not all comments are good comments. Explanatory comments that describe what code obviously does add noise without providing value. Comments like // Increment counter by one above counter++ insult the reader's intelligence and create maintenance burden without improving understanding, as noted in JavaScript.info.
The solution to unclear code is not more comments--it's better code. Before writing an explanatory comment, consider whether the code itself could be rewritten to be self-explanatory. Extract complex logic into named functions, use descriptive variable names, and simplify conditional logic. Self-documenting code reduces the need for comments while improving overall code quality.
When you do need to explain complex logic, focus on the "why" rather than the "what." The code shows what happens; the comment should explain why it happens that way. A comment explaining that "we sort by modified date because users expect recency" provides context that code cannot, while a comment restating the sort operation adds nothing.
Keeping Comments Current
The discipline of keeping comments current requires treating comment maintenance as part of code review. When modifying code, check whether existing comments require updates. When writing new code, write comments that are specific enough to remain accurate as the code evolves. Avoid vague comments that could become inaccurate through minor refactoring.
Some teams adopt a policy of removing comments rather than updating them, accepting that some loss of documentation is preferable to misleading documentation. Others implement automated tooling that flags comments likely to be outdated. Whatever approach you choose, make comment maintenance an explicit part of your workflow rather than an afterthought.
Performance and Comment Considerations
A common concern among developers new to web performance is whether comments affect runtime performance. The answer differs between CSS and JavaScript, and understanding these differences helps developers make informed decisions about comment usage.
For Next.js projects specifically, the framework's build pipeline handles both JavaScript and CSS optimization automatically. Developers can write comprehensive comments in source files without worrying about production impact. This removes the traditional trade-off between documentation and performance. See also our guide on Performance Optimization Techniques for related best practices.
Documentation-Driven Development in Next.js
Next.js encourages patterns that make documentation natural and valuable. Server Components, API routes, and type-safe data fetching all benefit from clear documentation because they involve complex interactions that are not obvious from code inspection alone. When working with Next.js, consider documenting server-side logic that affects client behavior, API route parameters and response shapes, and caching strategies that determine data freshness.
Documentation-driven development takes this further by treating comments as specifications to be verified. Write comments describing expected behavior before implementing, then verify that the implementation matches the documentation. This approach catches misunderstandings early and ensures documentation remains accurate throughout development, as noted in Frank M Taylor's guide. Our guides on Server Components Deep Dive and Data Fetching Strategies demonstrate these patterns in practice.
1/**2 * Fetches user data with caching strategy.3 * Server Component: Data fetched on server, never exposed to client4 * Cache: Revalidates every 60 seconds (ISR)5 * @param {string} userId - The user identifier6 * @returns {Promise<UserData>} User profile and preferences7 */8async function getUserData(userId: string) {9 const res = await fetch(`/api/users/${userId}`, {10 next: { revalidate: 60 }11 });12 return res.json();13}Building a Commenting Culture
Team Standards and Code Review
Sustainable commenting practices require team agreement on standards and consistent enforcement through code review. Without explicit standards, commenting becomes inconsistent--some team members document thoroughly while others add comments only when required. This inconsistency makes code harder to maintain and signals that commenting is optional rather than essential, as covered in Frank M Taylor's guide.
Effective commenting standards should specify which comment types are allowed and when they should be used, the format and structure for different comment categories, the process for handling outdated comments, and expectations for documentation coverage across different code types. See our Version Control Best Practices guide for how documentation integrates with collaborative workflows.
Code review is the enforcement mechanism for commenting standards. Reviewers should check not only for correct functionality but also for appropriate documentation. This includes verifying that new code includes necessary comments, existing comments remain accurate, and comment style matches team conventions. Over time, consistent enforcement makes commenting a habit rather than a chore.
The Long-Term Value of Well-Documented Code
The true value of comments emerges over time, when original developers have moved on and new developers inherit codebases they did not write. Well-documented code reduces onboarding time, prevents regressions, and enables confident modification of complex systems. These benefits compound over the life of a project, as noted in JavaScript.info.
Consider the developer who encounters a complex optimization in a performance-critical path. Without documentation, they must either invest significant time understanding the optimization or risk breaking it when making changes. With clear comments explaining the optimization's purpose, the trade-offs considered, and the expected behavior, the developer can make informed decisions quickly. This long-term perspective should influence commenting decisions at the time of writing.
Reduced Onboarding
New developers understand code faster with clear documentation explaining decisions and patterns.
Fewer Regressions
Comments prevent accidental breakage when modifying code others wrote.
Confident Changes
Clear documentation enables developers to modify code without fear of hidden side effects.
Summary
Effective commenting is a skill that improves with practice and intentionality. By focusing on explaining the 'why' rather than the 'what,' maintaining consistent formatting, and using comments to communicate context and reasoning, developers create codebases that serve their teams well over time.
The art lies in balance--enough comments to illuminate complex decisions, but not so many that they create noise. Modern build tools strip comments from production code, so write freely for development efficiency while trusting the deployment pipeline to optimize for end users.
Remember: the next person who reads your code--perhaps months or years from now--will thank you for comments that illuminate your reasoning and preserve the knowledge that went into each decision.