JavaScript Comments

Think of comments as "sticky notes" for your source code. They are snippets of text that the JavaScript engine completely ignores when running your program. While they don't change how your app functions, they are vital for explaining why you wrote code a certain way, helping both your future self and your teammates understand the logic behind the script.

Developer Tip: Use comments to explain the "intent" behind a block of code, rather than just describing what the code is doing. If the code is well-written, the "what" should be obvious; the "why" is where the value lies.

1. Single-Line Comments

Single-line comments are the most common type of comment in JavaScript. They begin with two forward slashes (//). Anything following these slashes on that same line will be treated as a comment and ignored by the browser.

// This is a standalone comment explaining the variable below
let userAge = 25; 

let price = 99; // This is an "inline" comment at the end of a line

Single-line comments are perfect for quick notes or temporarily disabling a single line of code while you are testing different solutions.

Common Mistake: Putting a single-line comment before a line of code, but forgetting that the comment only lasts until the end of that specific line. If your explanation wraps to a second line, you must start that new line with // as well.

2. Multi-Line Comments

Multi-line comments (also known as block comments) start with /* and end with */. They are ideal when you need to write a detailed explanation, document a function's parameters, or disable a large block of code during debugging.

/*
  The following function handles the user authentication.
  It checks the token validity and ensures the 
  session has not expired before granting access.
*/
function checkAccess() {
  // Logic goes here
}
Watch Out: You cannot nest multi-line comments. If you try to put a /* */ block inside another /* */ block, JavaScript will get confused and throw a SyntaxError because it will pair the first "/*" with the very next "*/" it finds.

Best Practices for Using Comments

Be Clear and Concise:

  • Write comments that provide immediate value. If a developer has to spend five minutes deciphering your comment, it’s not doing its job. Use plain, professional language.
Best Practice: Write your code as if the person who has to maintain it is a violent psychopath who knows where you live. Clear comments make for happy maintainers!

Update Comments Regularly:

  • Code evolves, and sometimes we forget to change the comments to match. An outdated comment is worse than no comment at all because it actively misleads other developers.

Avoid Redundant Comments:

  • If your code is clean and your variable names are descriptive, you don't need to comment every line.
Common Mistake: Commenting the obvious. For example:
let total = 5; // sets total to 5
This adds "noise" to your file without adding any new information.

Use Comments for Complex Logic:

  • If you are using a complex regular expression, a specific mathematical formula, or a "hack" to fix a bug in a specific browser, document it! This prevents someone else from "fixing" your code and accidentally breaking it again.

Don't Comment Obvious Code:

  • Strive for "self-documenting code." Instead of writing let d = 86400; // seconds in a day, write const SECONDS_IN_A_DAY = 86400;. This makes the code readable without needing a comment.

Follow a Consistent Style:

  • Whether you prefer single-line comments for everything or block comments for headers, stay consistent throughout your project to keep the codebase looking professional.

Example

Here is how a well-commented script might look in a real-world scenario, such as a shopping cart calculation:

// Calculate the final price after applying a seasonal discount
function getDiscountedTotal(price, discountPercentage) {
  // Ensure we don't divide by zero or process negative prices
  if (price <= 0) return 0;

  let discountAmount = (price * discountPercentage) / 100;
  return price - discountAmount;
}

/* 
  The following section initializes the checkout process.
  We use a hardcoded tax rate of 7% as per regional policy.
*/
const TAX_RATE = 0.07;
let cartTotal = 150.00; 

let finalPrice = getDiscountedTotal(cartTotal, 10); // Applying a 10% discount
Developer Tip: Many developers use comments starting with // TODO: to mark areas of the code that still need work. Most modern code editors (like VS Code) will highlight these so you don't forget to finish them later!