JavaScript Comments

Learn how to use comments in JavaScript to explain code, disable execution, and improve readability.


What Are Comments?

Comments are lines in your code that are ignored by the browser. They are used to:

  • Leave notes or reminders
  • Explain what the code does
  • Temporarily disable code without deleting it

Types of JavaScript Comments

1. Single-line Comments (//)

Use this to comment out one line or write a short explanation

// This is a single-line comment
let x = 5; // Set x to 5

2. Multi-line Comments (/* … */)

Use this when you want to comment out multiple lines or longer explanations.

/* This is a multi-line comment.
   It can span across several lines.
   Useful for block explanations. */
let y = 10;

Practical Use Cases

Explaining Code

// Calculate the total price including tax
let price = 100;
let taxRate = 0.18;
let total = price + (price * taxRate);

Disabling Code Temporarily

// alert("This message is temporarily disabled");
console.log("Only this will run");

Leaving TODOs or Notes

// TODO: Add user authentication
// Note: Change API endpoint in production

Full Example: Using All Comment Types

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Comments</title>
  <script>
    // This script demonstrates comments in JavaScript

    let name = "John"; // Assign name

    /* Greet the user.
       This block is for greeting only.
    */
    console.log("Hello, " + name + "!");

    // alert("This line is disabled");

    // TODO: Add user input instead of hardcoding the name
  </script>
</head>
<body>
  <h2>Check the console (F12) for output</h2>
</body>
</html>

Best Practices

PracticeTip
Keep comments short and relevantDon’t over-explain obvious code
Update comments with code changesOutdated comments can mislead
Use comments to organize your codeAdd headers or section titles
Don’t comment every single lineExplain logic, not syntax

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.