JavaScript Comments

Beginner 4 min read

Comments are notes in your code that JavaScript ignores. They help explain your code to other developers (and your future self). JavaScript supports single-line and multi-line comments.

Single-Line Comments

Use // to create a single-line comment. Everything after // on that line is ignored.

javascript
// This is a single-line comment
const name = "Alice";

const age = 25; // You can add comments at the end of a line

// Comments are ignored by JavaScript
// console.log("This won't run");

// Use single-line comments for:
// - Brief explanations
// - Temporarily disabling code
// - TODO notes
Keyboard Shortcut
In most code editors, press Ctrl+/ (Windows/Linux) or Cmd+/ (Mac) to toggle a comment on the current line.

Multi-Line Comments

Use /* to start and */ to end a multi-line comment. Also called "block comments".

javascript
/* This is a multi-line comment.
   It can span across multiple lines.
   Useful for longer explanations. */

const config = {
  /* Database configuration
     Host: localhost
     Port: 5432 */
  host: "localhost",
  port: 5432
};

/* You can also use it to disable code blocks:
const oldFunction = () => {
  console.log("This is disabled");
};
*/
No Nesting
You cannot nest multi-line comments. /* outer /* inner */ */ causes a syntax error because the first */ ends the comment.

JSDoc Comments

JSDoc is a documentation standard using /** */ syntax. IDEs use JSDoc to provide autocomplete, type hints, and documentation popups.

javascript
/**
 * Calculates the total price including tax.
 * @param {number} price - The base price
 * @param {number} taxRate - The tax rate as a decimal (e.g., 0.1 for 10%)
 * @returns {number} The total price with tax
 * @example
 * calculateTotal(100, 0.1) // returns 110
 */
function calculateTotal(price, taxRate) {
  return price * (1 + taxRate);
}

/**
 * Represents a user in the system.
 * @typedef {Object} User
 * @property {string} name - The user's name
 * @property {number} age - The user's age
 * @property {string} [email] - The user's email (optional)
 */

/**
 * Creates a new user.
 * @param {User} userData - The user data
 * @returns {User} The created user
 */
function createUser(userData) {
  return { ...userData, id: Date.now() };
}
Common JSDoc Tags
@param for parameters, @returns for return value, @example for usage examples, @typedef for custom types.

Special Comment Tags

Developers use special tags to mark code that needs attention. Most IDEs highlight these:

javascript
// TODO: Implement user authentication
function login(username, password) {
  // Placeholder implementation
  return true;
}

// FIXME: This breaks when array is empty
function getFirst(array) {
  return array[0];
}

// HACK: Workaround for browser bug in Safari
element.style.transform = "translateZ(0)";

// NOTE: This API is deprecated, migrate to v2
fetchDataV1();

// XXX: Needs refactoring - too complex
function processData(data) {
  // ... complex logic
}

Common Tags

TODO:Feature or task to implement later
FIXME:Known bug that needs fixing
HACK:Workaround that should be improved
NOTE:Important information about the code
XXX:Needs attention or refactoring

Try It Yourself

Experiment with different comment styles:

index.js
// This is a single-line comment
console.log("Hello!"); // Comment at end of line

/*
  This is a multi-line comment.
  It can span multiple lines.
  Useful for longer explanations.
*/

/**
 * Calculates the area of a rectangle.
 * @param {number} width - The width of the rectangle
 * @param {number} height - The height of the rectangle
 * @returns {number} The area of the rectangle
 */
function calculateArea(width, height) {
  return width * height;
}

const area = calculateArea(5, 3);
console.log("Area:", area);

// TODO: Add validation for negative numbers
// FIXME: Handle edge case when width equals 0

Best Practices

Good vs Bad Comments

javascript
// BAD: States the obvious
let count = 0; // Set count to 0

// BAD: Outdated comment (code changed, comment didn't)
// Increment by 1
count += 2;

// BAD: Commented-out code left forever
// function oldImplementation() {
//   return fetch('/old-api');
// }

// GOOD: Explains WHY
// Using localStorage for offline support when network is unavailable
const data = localStorage.getItem('cache') || fetchFromServer();

// GOOD: Documents a non-obvious fix
// CRITICAL: Timeout needed to prevent race condition with DOM update
setTimeout(() => updateUI(), 0);
1. Comment the 'Why', Not the 'What'
Good code is self-documenting. Comments should explain why you made a decision, not what the code does.
2. Keep Comments Updated
Outdated comments are worse than no comments. When you change code, update the comments.
3. Use JSDoc for Functions
Document public functions and APIs with JSDoc. It helps others use your code and provides IDE support.
4. Delete Commented-Out Code
Don't leave commented-out code in your codebase. Use version control (Git) to track old code.

Test Your Knowledge

Test Your Knowledge

4 questions
Question 1

Which syntax creates a single-line comment?

Question 2

What happens if you nest multi-line comments?

Question 3

What does JSDoc use to indicate a parameter?

Question 4

Which is a best practice for code comments?

Practice Exercise

Add JSDoc Comments

Easy

Add proper JSDoc comments to the functions, documenting their parameters, return values, and purpose.

Starter Code
// Challenge: Add proper JSDoc comments to these functions

function greet(name, greeting) {
  return greeting + ", " + name + "!";
}

function calculateDiscount(price, discountPercent) {
  if (discountPercent < 0 || discountPercent > 100) {
    return price;
  }
  return price * (1 - discountPercent / 100);
}

// Test the functions
console.log(greet("Alice", "Hello"));
console.log(calculateDiscount(100, 20));

Frequently Asked Questions

Do comments affect performance?

No. Comments are stripped out during parsing or minification. They have zero runtime impact. However, extremely large comment blocks could slightly slow down initial file parsing.

Should I comment every function?

Document public APIs and non-obvious functions with JSDoc. Private helper functions with clear names often don't need comments. The function name calculateTotalWithTax(price, rate) is self-documenting.

What's the difference between /** */ and /* */?

/* */ is a regular block comment. /** */ is a JSDoc comment that tools and IDEs parse for documentation. Use /** */ for function documentation.

Summary

JavaScript has two comment syntaxes:

  • Single-line: // for brief comments
  • Multi-line: /* */ for longer explanations
  • JSDoc: /** */ for documentation

Key takeaways:

  • Comment the why, not the what
  • Use JSDoc to document functions and APIs
  • Keep comments updated when code changes
  • Use TODO, FIXME, etc. to mark work in progress