JavaScript Comments
JavaScript comments can be used to explain code and make it more readable. Comments can also be used to prevent execution when testing.
Single Line Comments
Single line comments start with //. Any text between // and the end of the line is ignored by JavaScript.
Single Line Comments
// This is a single-line comment
let x = 5; // Declare x, set it to 5
let y = 10; // Declare y, set it to 10
console.log(x + y); // Output: 15Multi-line Comments
Multi-line comments start with /* and end with */. All text between /* and */ is ignored by JavaScript.
Multi-line Comments
/*
This function adds two numbers.
Parameters: a (number), b (number)
Returns: their sum
*/
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // 7Commenting Out Code
Comments can be used to prevent execution of code during testing.
Disabling Code with Comments
let message = "Hello!";
// console.log("This line is disabled");
console.log(message); // Only this runs
/*
let debug = true;
console.log("Debug mode on");
*/| Type | Syntax | Use When |
|---|---|---|
| Single-line | // text | Short inline notes |
| Multi-line | /* text */ | Long descriptions or block commenting |
| JSDoc | /** @param */ | Documenting functions for tools |
📝 Note: Single-line comments are the most common. Use multi-line comments for formal documentation.
Exercise:
How do you write a single-line comment in JavaScript?