JavaScript Tutorial
JavaScript Comments
Comments explain why. They never run. Use // for one line and /* */ for a block.
Comments never run
A comment is text for a human. The engine skips it. It does not print. It does not change the page. Use comments to record why a line exists, not to repeat what the code already shows.
Example
// This program greets once.
console.log("Hello");Run this in /javascript/try with Try it in JavaScript. Comments never appear in the console or on the page.
One line with //
Two slashes start a comment that runs to the end of that line. You can put // on its own line or after a statement. Everything after // on that line is skipped.
Example
let n = 10; // starting inventory
console.log(n);
// console.log("skip this line while testing");
console.log("still running");Commenting out a statement is a common way to disable it while you test. Delete the // when you want that line back.
A block with /* */
/* starts a comment that can span several lines. */ ends it. Everything between those markers is skipped, including what would otherwise be code.
Example
/*
Print a short header, then a number.
Block comments can cover more than one line.
*/
console.log("total");
console.log(42);A block comment can also sit in the middle of a line. That is legal. It is rarely clearer than a line comment.
Blocks do not nest
You cannot put one /* ... */ inside another. The first */ ends the comment. The rest of the inner comment becomes ordinary code, and the engine reports a mess of errors.
If you wrap a region in /* */ and that region already contains */, the comment stops too early. Prefer // on each line when you disable a chunk of code.
What to write
Name the intent, the unit, or the rule a reader would miss. Do not narrate n = n + 1 as “add one.” Stale comments are worse than none: when you change the code, change the comment in the same edit.
| Weak | Useful |
|---|---|
count = count + 1; // increment count | count = count + 1; // skip the header row |
price = price * 0.9; // multiply | price = price * 0.9; // 10 percent loyalty discount |
Comments are not strings
Text in quotes is data. The program can log it or put it on the page. Text after // is not data. If you need the user to see a message, put it in console.log ortextContent, not in a comment.
Example
// This never appears in the console.
console.log("This does.");HTML comments are different
HTML uses <!-- ... -->. That is not JavaScript. Inside a <script> tag, use // or /* */. Mixing the two is a common copy-paste error.
Next: variables — named boxes with let and const.