How Comments Work in JavaScript

When writing code, it’s helpful to leave little notes for yourself or others. These notes are called *comments*. They don’t affect how the code runs — they’re just there to explain, remind, or temporarily disable parts of your code. In JavaScript, adding comments is super easy, and it makes your code much more readable.

Single-line comments

The most common type of comment is a single-line comment. You use two forward slashes (//) and then write your note after them. Anything on the same line after // will be ignored by JavaScript.

javascript
          // This shows a welcome message
console.log('Hello, user!');
        

You can also place a single-line comment at the end of a line of code:

javascript
          let age = 25; // This is the user's age
        

Use single-line comments when you want to quickly explain a line or two of code.

Multi-line comments

If you want to write a longer note or comment out several lines, you can use a multi-line comment. These start with /* and end with */. Everything between those symbols will be ignored by the browser.

javascript
          /* 
This function shows a greeting to the user.
It will be improved in the next version.
*/
function greet() {
  console.log('Hi!');
}
        

Multi-line comments are also useful when you want to temporarily "turn off" a block of code while testing:

javascript
          /*
let score = 0;
console.log(score);
*/
        

This can help when you're trying to find bugs or test new ideas without deleting your code.

When and why to comment

You should add comments when your code might be confusing or when you want to explain why you did something a certain way. For example, if a piece of code solves a tricky issue or works around a bug, leave a note so you or someone else understands it later.

Good comments should be short and clear. Don’t over-comment things that are already obvious:

javascript
          let count = 5; // Setting count to 5 ❌ (this is too obvious)
        

But do comment when the code does something less obvious:

javascript
          // Using Math.random() to generate a number between 1 and 10
let randomNumber = Math.floor(Math.random() * 10) + 1;
        

Comments help make your code more professional, easier to understand, and easier to maintain—especially if you come back to it after a long time or if you're working with a team.