When your code does not work as expected, it has a "bug". Finding and fixing these bugs is called **debugging**. Comments are notes you write in your code that the computer ignores. You can use these notes to help you find bugs. This tutorial will teach you how to use comments as a powerful tool for debugging your JavaScript code. You will learn how to disable parts of your code, explain your thoughts, and mark problem areas.
Commenting for Debugging
Commenting for Debugging
A bug is a mistake in your code that makes it not work correctly. Debugging is the process of finding and fixing these bugs. JavaScript comments are special lines in your code that the computer skips over. They are only for humans to read.
You can use comments to temporarily turn off parts of your code. You can also use them to write down what you think is happening. This helps you track down problems step-by-step. It's like leaving sticky notes for yourself as you investigate a mystery.
What are Comments for Debugging?
Using comments for debugging means writing notes or temporarily disabling code sections to understand why your program is not working correctly. The computer ignores these notes.
Disable Code
Turn off a line or block of code to see if it causes the bug. The computer will ignore it.
Mark Problems
Highlight suspicious areas or lines where you think a bug might be hiding.
Explain Logic
Write down your thoughts about what code should do or what values it should have.
Temporary Notes
Add quick notes about what you are testing or what you changed recently.
What are Comments?
What are Comments?
In JavaScript, there are two main ways to write comments. You can use two forward slashes // for a single-line comment. Everything after // on that line is ignored.
For comments that span multiple lines, you use /* to start the comment and */ to end it. Everything between these two markers is ignored by JavaScript.
1// This is a single-line comment.2let score = 100; // You can also put a comment at the end of a line.34/*5This is a multi-line comment.6It can cover many lines of text.7Everything inside is ignored by the JavaScript engine.8*/9let playerName = "Hero";1011console.log(score); // This will print 10012console.log(playerName); // This will print "Hero"
Remove debugging comments before shipping
It is very important to remove or clean up your debugging comments before your code goes live to users. Leaving them in can make your code harder to read for others, and sometimes they can even expose sensitive information or slow down your code slightly.
How Comments Help You Debug
How Comments Help You Debug
Comments are useful for debugging because they let you change your code temporarily without deleting anything. If you think a line of code is causing a problem, you can comment it out. This means JavaScript will ignore that line, and you can see if the bug goes away.
You can also use comments to write down your guesses. For example, if you expect a variable to be a certain number, you can write a comment next to it saying // Should be 5 here. Then, if it's not 5, you know there's a problem earlier in your code.
1function calculateTotal(price, quantity) {2 let subtotal = price * quantity;3 // console.log("Subtotal before tax: ", subtotal); // This line is commented out for now45 // Let's assume there's a bug with the tax calculation.6 // This line might be causing an issue, so we'll comment it out to test.7 // let totalWithTax = subtotal * 1.05; // Original line for 5% tax89 // For testing, let's just return the subtotal to see if the bug is gone.10 return subtotal; // If the bug disappears, the tax line was the problem.11}1213let finalAmount = calculateTotal(10, 3);14console.log("Final amount: ", finalAmount); // Expected: 30
function processOrder(itemPrice, itemCount) {let orderTotal = itemPrice * itemCount;orderTotal = orderTotal + 5; // Shipping feeif (orderTotal > 100) {orderTotal = orderTotal * 0.9; // Apply discount}return orderTotal;}console.log(processOrder(20, 3)); // Expected 65, got 63. No idea why.
function processOrder(itemPrice, itemCount) {let orderTotal = itemPrice * itemCount; // Initial calculation: 20 * 3 = 60// console.log('After initial:', orderTotal); // Should be 60orderTotal = orderTotal + 5; // Add shipping fee: 60 + 5 = 65// console.log('After shipping:', orderTotal); // Should be 65if (orderTotal > 100) { // Is 65 > 100? No.orderTotal = orderTotal * 0.9; // This line should NOT run.}// console.log('After discount check:', orderTotal); // Should still be 65return orderTotal;}console.log(processOrder(20, 3)); // Expected 65, got 65. The comments helped confirm the logic.
Commenting vs. `console.log()`
Commenting vs. `console.log()`
Both comments and console.log() are helpful for debugging, but they do different jobs. console.log() prints the actual values of your variables to the console. This lets you see what your code is really doing.
Comments, on the other hand, let you disable code or write down your expected values or thoughts. They are good for testing different parts of your code without deleting them. Often, you will use both methods together.
function applyDiscount(price, discountRate) {// Let's assume the discount is applied incorrectly.// We will comment out the original line and test a simpler return.// return price * (1 - discountRate); // Original line// For now, just return the price to see if the issue is gone.return price;}let finalPrice = applyDiscount(100, 0.10);console.log(finalPrice); // If this is 100, the original line had the bug.
function applyDiscount(price, discountRate) {let discountedPrice = price * (1 - discountRate);console.log('Original Price:', price); // Check the input priceconsole.log('Discount Rate:', discountRate); // Check the input rateconsole.log('Calculated Discounted Price:', discountedPrice); // See the resultreturn discountedPrice;}let finalPrice = applyDiscount(100, 0.10);// console.log(finalPrice); // This will print the final result after logs.
function applyDiscount(price, discountRate) {// Let's assume the discount is applied incorrectly.// We will comment out the original line and test a simpler return.// return price * (1 - discountRate); // Original line// For now, just return the price to see if the issue is gone.return price;}let finalPrice = applyDiscount(100, 0.10);console.log(finalPrice); // If this is 100, the original line had the bug.
function applyDiscount(price, discountRate) {let discountedPrice = price * (1 - discountRate);console.log('Original Price:', price); // Check the input priceconsole.log('Discount Rate:', discountRate); // Check the input rateconsole.log('Calculated Discounted Price:', discountedPrice); // See the resultreturn discountedPrice;}let finalPrice = applyDiscount(100, 0.10);// console.log(finalPrice); // This will print the final result after logs.
When to use which
Use comments when you want to temporarily remove a piece of code, or when you want to write down your thoughts and expectations. Use console.log() when you need to see the actual value of a variable at a specific moment in your program's execution.
Real-World Debugging with Comments
Real-World Debugging with Comments
Imagine you have a function that calculates a user's total score in a game, but it's giving the wrong answer. You can use comments to isolate the problem. You will start by commenting out parts of the function to see where the error might be. This helps you narrow down the buggy section.
Identify a suspicious function
Find the function that seems to be causing the incorrect result. Let's say it's calculateGameScore.
1function calculateGameScore(baseScore, bonusPoints, penalty) {2 let total = baseScore + bonusPoints;3 total = total - penalty;4 total = total * 2; // This line is suspicious!5 return total;6}7let finalScore = calculateGameScore(100, 50, 20);8console.log("Final Score:", finalScore); // Expected: 130, Got: 260
Comment out the last problematic part
If the result is 260 instead of 130, it looks like something multiplied the result by 2. Comment out the last calculation line to see if the issue goes away.
1function calculateGameScore(baseScore, bonusPoints, penalty) {2 let total = baseScore + bonusPoints;3 total = total - penalty;4 // total = total * 2; // Commented out this suspicious line5 return total;6}7let finalScore = calculateGameScore(100, 50, 20);8console.log("Final Score:", finalScore); // Expected: 130, Got: 130! Found the bug.
Fix the bug and remove debugging comments
Now that you found the line causing the problem, you can fix it. Then, remove any temporary debugging comments you added to keep your code clean.
1function calculateGameScore(baseScore, bonusPoints, penalty) {2 let total = baseScore + bonusPoints;3 total = total - penalty;4 // The line 'total = total * 2;' was the bug. It is now removed or fixed.5 return total;6}7let finalScore = calculateGameScore(100, 50, 20);8console.log("Final Score:", finalScore); // Correct: 130
Comments are not a replacement for testing
While comments help you understand and isolate issues, they don't find the bug for you. You still need to test your code after making changes. Always check if your fixes actually solve the problem and don't create new ones.
Comment Types and Best Practices
Comment Types and Best Practices
| Comment Type | Syntax | Use for Debugging | Best Practice |
|---|---|---|---|
| Single-line | `// ...` | Temporarily disable one line, add quick notes, explain a single variable. | Use for short, specific comments or disabling single lines. |
| Multi-line | `/* ... */` | Disable a block of code, explain complex logic, add detailed thoughts about a bug. | Use for larger blocks of text or turning off multiple lines of code. |
Test Your Knowledge
Test Your Knowledge
Which type of comment is best for temporarily disabling a single line of JavaScript code?
When debugging, why might you comment out a block of code?
What is the main difference between using console.log() and comments for debugging?
Is it a good practice to leave all debugging comments in your code when it goes live?
Quick Reference
Quick Reference
- 1Debugging — finding and fixing mistakes (bugs) in your code.
- 2Comments — notes in your code that the computer ignores, only for humans.
- 3Single-line comments — use
//to comment out one line or add short notes. - 4Multi-line comments — use
/* ... */to comment out blocks of code or add longer explanations. - 5Disable code — use comments to temporarily turn off suspicious lines or blocks to test if they cause a bug.
- 6Explain logic — write comments to clarify what a section of code is supposed to do or what values variables should hold.
- 7Mark problem areas — use comments to highlight parts of your code that you suspect have issues.
- 8Combine with
console.log()— use comments to disable, andconsole.log()to inspect actual values. - 9Remove before production — always clean up temporary debugging comments before your code goes live to users.
- 10No performance impact — comments do not slow down your JavaScript program; the engine ignores them.
`console.log()` Deep Dive
Learn more advanced ways to use console.log() for inspecting values and tracking execution flow.
Browser Developer Tools
Discover powerful debugging features in your web browser, like breakpoints and inspecting variables.
Understanding JavaScript Errors
Learn about common JavaScript error messages and what they mean, so you can fix them faster.
Basic Error Handling
Explore how to use try...catch blocks to gracefully handle errors in your code.
You're now a debugging comment pro!
You've learned how to use JavaScript comments to effectively debug your code. This simple tool helps you isolate problems, explain your thinking, and track down those pesky bugs. Keep practicing, and you'll become a master debugger!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.