JavaScript

JavaScript Comments: Complete Guide for Beginners

8 min read Harshit No comments
JavaScript Comments

JavaScript comments are used to explain code, improve readability, and temporarily disable code during development. Comments are ignored by the JavaScript engine, so they do not affect the program’s execution.

When working on small scripts or large applications, writing clear comments can help you and other developers understand what the code does and why a particular approach was used.

In this tutorial, you will learn about single-line comments, multi-line comments, documentation comments, and best practices for writing comments in JavaScript.

What Are Comments in JavaScript?

Comments are text written inside your code that JavaScript does not execute as a program statement.

For example:

// This is a JavaScript comment
let name = "Harshit";

console.log(name);

Output:

Harshit

The JavaScript engine ignores the comment and executes the remaining code.

Comments are useful for:

  • Explaining complex logic.
  • Making code easier to understand.
  • Providing notes for other developers.
  • Temporarily disabling code while debugging.
  • Documenting functions and APIs.

JavaScript supports two main types of comments:

  1. Single-line comments
  2. Multi-line comments

Let’s explore them with examples.

1. Single-Line Comments in JavaScript

A single-line comment begins with two forward slashes (//). Everything after // on that line is treated as a comment.

Example

// Store the user's name
let name = "Harshit";

// Display the name
console.log(name);

Output:

Harshit

In this example, the comments explain the purpose of each statement.

Single-Line Comments After Code

You can also write a comment at the end of a line.

let age = 25; // Store the user's age

console.log(age); // Display the age

Output:

25

JavaScript executes the code before the comment and ignores the comment itself.

When Should You Use Single-Line Comments?

Use single-line comments when you need to:

  • Explain a specific statement.
  • Describe a variable’s purpose.
  • Clarify a condition or calculation.
  • Add a short note to a section of code.

For example:

let price = 1000;
let discount = 200;

// Calculate the final price after discount
let finalPrice = price - discount;

console.log(finalPrice);

Output:

800

2. Multi-Line Comments in JavaScript

Multi-line comments begin with /* and end with */. You can write comments across multiple lines.

Example

/*
This program calculates the total price
of a product after applying a discount.
*/

let price = 1000;
let discount = 200;

let finalPrice = price - discount;

console.log(finalPrice);

Output:

800

Everything between /* and */ is treated as a comment.

Using Multi-Line Comments to Explain Logic

let age = 20;

/*
Check whether the user is at least 18.
If the condition is true, display an
adult message.
*/

if (age >= 18) {
    console.log("You are an adult.");
}

Output:

You are an adult.

Multi-line comments are useful when a short explanation is not enough.

3. Temporarily Disabling Code with Comments

Developers sometimes comment out code while testing or debugging an application.

For example:

let a = 10;
let b = 20;

console.log(a + b);

// console.log(a - b);
// console.log(a * b);

Output:

30

The subtraction and multiplication statements are not executed because they are commented out.

You can also temporarily disable a block of code using a multi-line comment:

/*
let username = "Harshit";
console.log(username);
*/

console.log("Program started");

Output:

Program started

Important: Do not use comments as a permanent replacement for removing unused or unnecessary code. Old code can make projects harder to maintain.

4. Documentation Comments in JavaScript

Documentation comments are commonly written using the JSDoc style. They begin with /** and are used to describe functions, parameters, return values, and other code elements.

These comments help developers understand how a function should be used. Tools and IDEs can also use JSDoc annotations to provide documentation and type information.

Example

/**
 * Adds two numbers.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The sum of both numbers.
 */
function add(a, b) {
    return a + b;
}

console.log(add(10, 20));

Output:

30

In this example:

  • @param describes a function parameter.
  • @returns describes the returned value.
  • {number} indicates the expected type in the documentation.

JSDoc annotations describe the intended usage of the function. They do not automatically enforce these types at runtime in JavaScript.

Why Use JSDoc?

JSDoc is useful when:

  • Building reusable functions.
  • Working on team projects.
  • Creating libraries or APIs.
  • Documenting parameters and return values.
  • Improving editor suggestions and code navigation.

5. JavaScript Comments in HTML and CSS

When writing JavaScript inside an HTML file, JavaScript comments still use JavaScript syntax.

<script>
    // JavaScript single-line comment

    /*
       JavaScript multi-line comment
    */

    console.log("Hello World");
</script>

Remember that HTML and CSS use different comment syntax.

HTML comment:

<!-- This is an HTML comment -->

CSS comment:

/* This is a CSS comment */

Do not use HTML comment syntax as a replacement for JavaScript comments inside ordinary JavaScript code.

6. Best Practices for Writing JavaScript Comments

Writing comments does not automatically make code better. Good comments provide useful information that is not obvious from the code itself.

Explain Why, Not Just What

Less useful:

// Add 1 to count
count++;

The code already explains what is happening.

More useful:

// Start numbering from 1 because the UI uses one-based numbering
count++;

The second comment explains the reason behind the operation.

Keep Comments Updated

If the code changes, update the related comments as well. Incorrect comments can be more confusing than having no comments.

Avoid Unnecessary Comments

Avoid adding comments to every obvious statement.

Less useful:

// Create a variable
let name = "Harshit";

// Print the name
console.log(name);

For simple code, clear variable names may be enough.

Use Comments to Explain Complex Logic

// Apply the discount only when the order total reaches the minimum amount
if (total >= minimumOrderAmount) {
    total -= discount;
}

This comment explains the business rule behind the condition.

Do Not Store Sensitive Information in Comments

Avoid putting passwords, API secrets, access tokens, or private customer information in source-code comments. Comments can become visible in public repositories or compiled and deployed source files.

7. Common Mistakes with JavaScript Comments

Mistake 1: Forgetting to Close a Multi-Line Comment

Incorrect:

/*
This comment is not closed.

console.log("Hello");

The missing */ causes a syntax error because the comment is never properly terminated.

Correct:

/*
This comment is closed correctly.
*/

console.log("Hello");

Mistake 2: Nesting Multi-Line Comments

JavaScript does not support nested block comments.

Incorrect:

/*
Outer comment

/*
Inner comment
*/

console.log("Hello");
*/

The first */ closes the outer comment. The remaining text can then cause a syntax error.

Use single-line comments inside a block of notes or rewrite the comments to avoid nesting.

Mistake 3: Expecting Comments to Execute

// console.log("Hello");

Nothing is printed because the statement is commented out.

Remove the // if you want the statement to execute.

8. JavaScript Comments: Quick Reference

Comment typeSyntaxCommon use
Single-line// commentShort notes
Multi-line/* comment */Longer explanations
Documentation/** comment */Function and API documentation
HTML<!-- comment -->HTML files
CSS/* comment */CSS files

HTML and CSS comments are included here for comparison; they are not additional JavaScript comment types.

Frequently Asked Questions

What are comments in JavaScript?

Comments are notes in source code that the JavaScript engine ignores during normal execution. They help developers explain code and document decisions.

How do you write a single-line comment in JavaScript?

Use two forward slashes (//).

// This is a comment

How do you write a multi-line comment in JavaScript?

Start with /* and end with */.

/*
This is a
multi-line comment.
*/

What is the difference between // and /* */?

// comments out the rest of the current line. /* */ creates a block comment that can span multiple lines.

What is JSDoc in JavaScript?

JSDoc is a documentation style that uses comments beginning with /** and tags such as @param and @returns to describe functions, parameters, and return values.

Do comments affect JavaScript performance?

Comments do not affect the program’s normal logic or output. JavaScript tooling may remove comments during minification, and engines generally ignore them during execution.

Can comments be used to hide sensitive information?

No. Comments are not a secure place to store secrets. Source code and comments may be visible to other developers or users, so sensitive information should be kept out of them.

Practice Exercises

Try these exercises to practise writing JavaScript comments:

  1. Write a single-line comment above a variable declaration.
  2. Add a comment at the end of a JavaScript statement.
  3. Write a multi-line comment explaining a simple calculator.
  4. Comment out a console.log() statement.
  5. Write a function that calculates the square of a number.
  6. Add JSDoc comments describing the function’s parameter and return value.
  7. Review a code example and remove unnecessary comments.
  8. Write a comment explaining why a particular condition is required.

Conclusion

JavaScript comments help make code easier to understand, document functions, explain business rules, and temporarily disable code during debugging.

Remember the two main comment syntaxes: // for single-line comments and /* */ for multi-line comments. For documenting reusable functions and APIs, learn the JSDoc style.

Write comments when they add meaningful information, keep them updated, and never use them to store sensitive data.

In the next tutorial, we will learn about JavaScript Conditional Statements, including if, else, else if, and switch.

Leave a comment

Your email address will not be published.