JavaScript Comments
JavaScript comments let you leave human-readable notes in your code that the engine ignores when the program runs.
What are comments?
A comment is any text in a source file that JavaScript deliberately skips over during execution. Comments exist purely for the people who read the code later, including you, and have no effect on the result the program produces. They are one of the simplest yet most valuable tools for keeping a codebase understandable as it grows.
JavaScript offers two comment styles: single-line comments that begin with two forward slashes, and multi-line comments wrapped between a slash-star and a star-slash. Both are supported everywhere JavaScript runs, from browsers to Node.js.
Single-line comments
Anything following // on the same line is treated as a comment. You can place a single-line comment on its own line above the code it describes, or at the end of a line of code to annotate that specific statement.
Using single-line comments
<!DOCTYPE html>
<html>
<body>
<h2>Single-line Comments</h2>
<script>
// Calculate the area of a rectangle
const width = 8;
const height = 5;
const area = width * height; // area is now 40
console.log(area);
</script>
</body>
</html>Multi-line comments
When a note spans several lines, wrap it between /* and */. Everything between those markers is ignored, no matter how many lines it covers. This style is handy for longer explanations or for temporarily removing a block of code while you test something.
Using multi-line comments
<!DOCTYPE html>
<html>
<body>
<h2>Multi-line Comments</h2>
<script>
/*
This function converts a temperature
from Celsius to Fahrenheit and returns
the result as a number.
*/
function toFahrenheit(celsius) {
return celsius * 9 / 5 + 32;
}
console.log(toFahrenheit(20)); // 68
</script>
</body>
</html>Commenting out code
A common everyday use of comments is to disable a line or block of code without deleting it. This is useful while debugging when you want to see how the program behaves with certain statements switched off. In most editors the shortcut Ctrl+/ (or Cmd+/ on macOS) toggles comments for the selected lines.
Temporarily disabling a line
<!DOCTYPE html>
<html>
<body>
<h2>Commenting Out Code</h2>
<script>
let total = 100;
// total = total * 2; <-- disabled for now
total = total + 10;
console.log(total); // 110
</script>
</body>
</html>Comment style at a glance
Exercise: JavaScript Comments
How do you write a single-line comment in JavaScript?