JavaScript Comments
Adding notes and documentation to your code
💬 What are JavaScript Comments?
Comments are text notes in your code that are ignored by the JavaScript engine. They help explain what your code does and make it easier to understand.
// This is a single-line comment
let name = "John"; // Comment at end of line
/* This is a
multi-line comment */
let age = 25;
Output:
name = "John"
age = 25
Types of Comments
Single-line
Comments that span one line
// This is a single-line comment
let x = 5;
Multi-line
Comments that span multiple lines
/* This comment
spans multiple
lines */
Inline
Comments at the end of code lines
let y = 10; // Set y to 10
Code Disable
Temporarily disable code
// console.log("Debug");
let z = 15;
🔹 Single-line Comments
Single-line comments start with // and continue to the end of the line:
// This is a comment
let firstName = "John";
let lastName = "Doe"; // Another comment
// You can use multiple single-line comments
// to create a block of comments
let fullName = firstName + " " + lastName;
Output:
firstName = "John"
lastName = "Doe"
fullName = "John Doe"
🔹 Multi-line Comments
Multi-line comments start with /* and end with */:
/*
This is a multi-line comment.
It can span multiple lines.
Everything between /* and */ is ignored.
*/
let score = 100;
/*
You can also use multi-line comments
to temporarily disable blocks of code
let tempVar = "disabled";
console.log(tempVar);
*/
Output:
score = 100
🔹 Best Practices for Comments
Here are some guidelines for writing good comments:
// Good: Explain WHY, not WHAT
let taxRate = 0.08; // Sales tax rate for California
// Good: Explain complex logic
if (age >= 18 && hasLicense && !hasViolations) {
// Allow driving only if all conditions are met
allowDriving = true;
}
// Avoid: Obvious comments
let x = 5; // Set x to 5 (unnecessary)
// Good: Document function purpose
function calculateTotal(price, tax) {
// Calculate final price including tax
return price + (price * tax);
}
Output:
Well-documented code is easier to understand and maintain