Comments in JavaScript: A Beginner’s Guide

4/13/2025

#Comments in JavaScript: A Beginner’s Guide

Go Back

Comments in JavaScript: A Beginner’s Guide

Comments are an essential part of writing clean, readable, and maintainable code. In JavaScript, comments are used to explain code, leave notes for future developers, or temporarily disable code during debugging.

This tutorial covers the different types of comments in JavaScript and best practices for using them.


#Comments in JavaScript: A Beginner’s Guide

1. Single-line Comments

Use // to write a single-line comment.

✅ Example:

// This is a single-line comment
let name = "John"; // This comment is next to a line of code

Single-line comments are often used to describe a specific line or a short block of logic.


2. Multi-line Comments

Use /* */ to write comments that span multiple lines.

✅ Example:

/*
  This is a multi-line comment.
  It can span several lines.
*/
let age = 30;

Multi-line comments are useful for explaining complex logic or sections of code.


3. Commenting Out Code

Sometimes you may want to temporarily disable code without deleting it.

✅ Example:

// let price = 100;
// console.log(price);

This technique is handy when debugging or testing changes.


4. Documentation Comments (JSDoc)

JSDoc comments are a special form of multi-line comments used for documenting functions, classes, and APIs. They begin with /**.

✅ Example:

/**
 * Adds two numbers.
 * @param {number} a - First number
 * @param {number} b - Second number
 * @returns {number} Sum of a and b
 */
function add(a, b) {
  return a + b;
}

JSDoc comments are especially useful in larger projects and for generating documentation.


5. Best Practices for Using Comments

  • ✅ Keep comments clear and concise.

  • ✅ Use comments to explain "why," not "what."

  • ❌ Avoid obvious comments:

// Add 1 to i
i++; // This is self-explanatory and doesn’t need a comment
  • ✅ Keep comments up-to-date with your code.


Final Thoughts

Good comments can greatly improve code readability and maintainability. Whether you're collaborating on a team or revisiting your own code after months, well-placed comments will always make your job easier.

Use single-line and multi-line comments wisely, and consider adopting JSDoc for professional-level documentation!

Table of content