A comment is a special note you write in your code. The computer ignores comments, but people can read them. Single-line comments help you add quick notes or turn off one line of code. This tutorial teaches you how to use `//` for single-line comments.
Single-line Comments (//)
Single-line Comments (//)
In JavaScript, a comment is text that the computer completely ignores when it runs your program. Comments are for humans to read. They help you explain what your code does.
There are two types of comments in JavaScript: single-line comments and multi-line comments. This page focuses on single-line comments, which start with two forward slashes (//). Everything after // on that line becomes a comment.
What is a Comment?
A comment is a piece of text in your code that is ignored by the computer. Its only purpose is to help people understand the code.
Explain Code
Use comments to describe what complex parts of your code are doing, making it easier to understand.
Disable Code
Temporarily turn off a line of code without deleting it, useful for testing or debugging.
Add Notes
Leave reminders for yourself or other developers, like 'TODO' items or future improvements.
Improve Readability
Well-placed comments make your entire program clearer and easier for anyone to follow.
How to Write Single-line Comments
How to Write Single-line Comments
To write a single-line comment, you simply type two forward slashes (//). Everything that comes after // on that same line will be treated as a comment.
The computer will completely ignore this text. It will not try to run it as code. This means you can write anything you want in a comment.
1// This is a single-line comment. The computer ignores it.23let score = 100; // This comment explains what 'score' is for.45// console.log('This line is commented out and will not run.');67console.log(score); // Output: 10089// You can put comments on their own line too.
Don't forget the slashes!
If you forget to put // at the start of your comment, JavaScript will try to run your text as code. This will cause an error because your notes are not valid code.
This is a note; // ❌ SyntaxError: Unexpected identifier
let x = 10;
Why Comments are Important
Why Comments are Important
Comments are like sticky notes for your code. They help you remember why you wrote something a certain way. They also help other people understand your code when they read it.
Good comments make your code much easier to maintain. They save time when you or someone else needs to fix or change the program later.
1let userAge = 15;23// Check if the user is old enough to access content4// This condition uses an 'if' statement to compare age.5if (userAge >= 18) {6 console.log('Access granted.');7} else {8 console.log('Access denied. Must be 18 or older.');9 // console.log('Consider showing a different message for younger users.'); // Temporarily disabled10}1112// TODO: Add a feature to verify age with a birthdate input.
function calculateTotal(p, t) {let sub = p * t;let final = p + sub;return final;}
// This function calculates the total price including tax.// p: product price, t: tax rate (e.g., 0.05 for 5%)function calculateTotal(price, taxRate) {let taxAmount = price * taxRate; // Calculate the tax amountlet finalPrice = price + taxAmount; // Add tax to the original pricereturn finalPrice; // Return the total price}
Different Ways to Use Single-line Comments
Different Ways to Use Single-line Comments
You can place a single-line comment in two main ways. You can put it on its own line, above the code it explains. Or, you can put it at the very end of a line of code. Both ways are correct and useful.
The choice depends on how much you need to explain. A full line comment is good for complex logic. An end-of-line comment is good for quick notes.
// Define a constant for the maximum number of attempts allowed.const MAX_ATTEMPTS = 3;// Initialize the user's score to zero before starting the game.let userScore = 0;
const MAX_ATTEMPTS = 3; // Maximum retries for loginlet userScore = 0; // Starting score for the playerlet userName = 'Guest'; // Default user name
// Define a constant for the maximum number of attempts allowed.const MAX_ATTEMPTS = 3;// Initialize the user's score to zero before starting the game.let userScore = 0;
const MAX_ATTEMPTS = 3; // Maximum retries for loginlet userScore = 0; // Starting score for the playerlet userName = 'Guest'; // Default user name
When to use each style
Use a comment on its own line when you need to explain a bigger idea or a block of code. Use a comment at the end of a line for short, quick notes about that specific line, like explaining a variable's purpose.
Using Comments in Real-World Code
Using Comments in Real-World Code
In real programming, comments are used all the time. They help teams work together. They also help you when you come back to your own code after a long time. Think of them as signposts in your code.
Good comments are clear, concise, and helpful. They don't just repeat what the code does; they explain why it does it.
Explain a complex function
Add comments before a function to describe what it does, what inputs it needs, and what it returns.
1// This function calculates the area of a rectangle.2// It takes two numbers: 'width' and 'height'.3// It returns a single number: the calculated area.4function calculateRectangleArea(width, height) {5 return width * height;6}
Mark a 'TODO' for future work
Use // TODO: comments to remind yourself or others about unfinished tasks or improvements.
1let userName = 'Alice';23// TODO: Implement user authentication and login system.4if (userName === 'Alice') {5 console.log('Welcome back, Alice!');6} else {7 console.log('Hello, Guest!');8}
Temporarily disable code for debugging
If a line of code is causing issues, you can 'comment it out' to temporarily stop it from running without deleting it.
1let debugMode = true;23if (debugMode) {4 console.log('Debugging messages are ON.');5 // console.log('Current user data: ' + JSON.stringify(userData)); // This line is commented out6 console.log('Database connection status: OK');7}
Avoid outdated or misleading comments
A comment that is wrong or outdated is worse than no comment at all. If you change your code, always remember to update any related comments. Old comments can confuse people and lead to bugs.
Comment Best Practices and Types
Comment Best Practices and Types
| Comment Type | Syntax | Purpose | Best Use Cases |
|---|---|---|---|
| Single-line Comment | `// comment text` | Short notes, explanations, disabling code. | Inline explanations, temporary code disablement, quick 'TODO's. |
| Multi-line Comment | `/* comment text */` | Longer explanations, block descriptions. | File headers, function documentation, explaining algorithms. |
Test Your Knowledge
Test Your Knowledge
Which symbol starts a single-line comment in JavaScript?
What is the primary purpose of a comment in code?
What happens if you forget // before a comment?
Which of these is a good use case for a single-line comment?
Quick Reference
Quick Reference
- 1Comments — text in your code that the computer ignores.
- 2Single-line comment — starts with
//and comments out the rest of that line. - 3Purpose — to make code understandable for humans, not for the computer.
- 4Explanation — use
//to explain what and why your code does something. - 5Temporary disable — place
//in front of a line of code to stop it from running. - 6Inline notes — put
//at the end of a line of code for quick, specific notes. - 7Block comments — for longer explanations, use multi-line comments
/* ... */. - 8Readability — good comments greatly improve how easy your code is to read and maintain.
- 9Stay updated — always update comments if you change the code they describe.
- 10Avoid redundancy — don't comment on obvious code; comment on non-obvious logic.
Multi-line Comments
Learn how to write longer comments that span multiple lines using /* ... */ syntax.
Code Documentation
Explore how comments can be used with tools like JSDoc to generate official project documentation.
Code Style Guides
Understand how coding conventions dictate where and how to use comments effectively.
Debugging Techniques
See how commenting out code is a fundamental technique for finding and fixing errors.
You now understand Single-line Comments!
You've learned how to use // to add notes, explain code, and temporarily disable lines. Single-line comments are a simple yet powerful tool for making your JavaScript programs clearer and easier to manage.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.