Ch 9 / 78
JavaScript Beginner Chapter 5

Comments

Comments are lines in your code that the JavaScript engine completely ignores. They exist purely for humans — to explain logic, document intent, and make complex code understandable months later.

What you'll learn in this chapter
Write single-line comments with //
Write multi-line comments with /* */
Comment out code for debugging
Write JSDoc documentation comments
Best practices: what to comment and what not to
Use TODO / FIXME / HACK markers

The Two Types of Comments

JavaScript supports two comment syntaxes. Both are completely ignored by the engine — they produce zero output and have no effect on how the code runs.

01 — Single-line
// Line Comment
// This is a single-line comment
Everything after // on that line is ignored. Most commonly used for short explanations and inline notes.
02 — Multi-line
/* Block Comment */
/* This spans
multiple lines */
Everything between /* and */ is ignored, regardless of line breaks. Used for longer explanations and JSDoc.

Single-Line Comments — //

Single-line comments start with // and run to the end of the line. They can appear on their own line or after code on the same line (inline comments).

JS — single-line comments
// This whole line is a comment — fully ignored by JS

let age = 25; // inline comment — code runs, comment is ignored

// Variables for storing user data
let firstName = "Alice";
let lastName  = "Smith";

// Calculate birth year (approximate)
let currentYear = 2025;
let birthYear = currentYear - age; // 2000

// Commenting out code during debugging:
// console.log("This line won't run");
console.log("This one runs");

Multi-Line Block Comments — /* */

Block comments start with /* and end with */. Everything in between — including newlines — is treated as a comment.

JS — multi-line block comments
/*
  This is a multi-line comment.
  It can span as many lines as you need.
  Great for detailed explanations.
*/

function calculateTax(income, rate) {
    /*
      Tax formula:
        1. Multiply income by the rate (as a decimal)
        2. Round to 2 decimal places
        Note: rate is passed as percentage (e.g. 20 for 20%)
    */
    return Math.round((income * rate / 100) * 100) / 100;
}

/* Can also be used inline — not recommended, but valid */
let x = 5 + /* this 3 is ignored */ 3;
console.log(x); // 8

Commenting Out Code

One of the most practical uses of comments during development is temporarily disabling code without deleting it. This is called "commenting out".

JS — commenting out for debugging
function processOrder(order) {
    console.log("Processing:", order);

    // Temporarily disabled while testing new logic below:
    // sendEmailConfirmation(order.email);
    // updateDatabase(order);

    // New logic being tested:
    queueForProcessing(order);
}

/*
  Entire section disabled during refactoring:

  function oldPaymentFlow(amount) {
    const result = legacyPaymentAPI(amount);
    return result.status === 200;
  }
*/
VS Code Shortcut
In VS Code, select any lines and press Ctrl + / (Windows/Linux) or Cmd + / (Mac) to toggle comments on/off instantly. For block comments use Shift + Alt + A.

JSDoc — Documentation Comments

JSDoc is a standard format for documenting JavaScript functions, parameters, and return values using specially formatted block comments. Editors like VS Code read JSDoc and show it as intelligent tooltips when you hover over function calls.

JSDoc Format
/**
* Calculates the total price including tax.
*
* @param {number} price - The base price before tax
* @param {number} taxRate - Tax rate as a percentage (e.g. 18)
* @returns {number} Total price rounded to 2dp
*/
function getTotalPrice(price, taxRate) {
  return Math.round(price * (1 + taxRate / 100) * 100) / 100;
}
JS — JSDoc examples
/**
 * Greets a user by name.
 *
 * @param {string} name - The user's first name
 * @returns {string}    - The greeting message
 */
function greetUser(name) {
    return `Hello, ${name}! Welcome to K2infocom. 🎉`;
}

/**
 * Finds a user by their ID.
 *
 * @param {number}  id       - The user's unique ID
 * @param {boolean} [active] - Optional: only search active users
 * @returns {Object|null}    - The user object, or null if not found
 */
function findUser(id, active = true) {
    // implementation here...
}

Comment Best Practices

Not all comments are created equal. Good comments explain the why, not the what. The code already shows what is happening — the comment should explain the intent, context, or any non-obvious decision.

✓ Good comments
// Retry up to 3 times — API is flaky under load
const MAX_RETRIES = 3;

// Using Math.floor not parseInt — safer for
// non-integer inputs (parseInt("3abc") = 3)
const index = Math.floor(value);

// TODO: replace with pagination once API supports it
const all = fetchAll();
✗ Useless comments
// Set x to 5
let x = 5;

// Add a and b
let sum = a + b;

// Loop through users array
users.forEach(u => process(u));

TODO, FIXME & HACK Markers

Convention markers help teams track pending work in code. VS Code and most IDEs highlight these automatically, and tools like todo-tree list them all in a sidebar.

JS — conventional comment markers
// TODO: add input validation before deploying
function saveUser(data) {
    database.insert(data);
}

// FIXME: this breaks when timezone offset is negative
function formatDate(date) {
    return date.toISOString().split('T')[0];
}

// HACK: workaround for Safari bug — remove after iOS 18
if (isSafari()) {
    element.style.transform = 'translateZ(0)';
}

// NOTE: this function is intentionally synchronous
function readConfig() { /* ... */ }
⚡
Free Resource
Download our JavaScript Best Practices Guide
Naming, comments, error handling, and code structure on one page.
Get Guide

Try It Yourself

Practice adding comments to the code below. Try commenting out one of the lines to see it stop running.

Live Editor
✎ HTML / JS
👁 Preview
Quick Check — Chapter 5

Which comment syntax is used to write multi-line documentation (JSDoc)?

Chapter Summary
  • // creates a single-line comment — everything after it on that line is ignored.
  • /* */ creates a multi-line block comment — spans as many lines as needed.
  • Comments are completely ignored by the JS engine — zero performance cost.
  • Use /** */ (JSDoc) to document functions — editors show it as hover tooltips.
  • Good comments explain the why, not the what. Avoid restating what the code already shows.
  • Use TODO / FIXME / HACK / NOTE markers to flag pending work and known issues.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel