Getting startedChapter 6 of 21
Comments
Notes the engine ignores, and what is worth writing in them.
Two forms
Everything after // on a line is ignored. Everything between /* and */ is ignored, across as many lines as you like.
JavaScript
// A note to whoever reads this next.
const rate = 0.19;
/* Several lines,
for a longer explanation. */
console.log(rate);Output
0.19
Commenting code out
Both forms are used to disable code while working. It is a fast way to isolate a problem, and it should not survive into work you share: version control already remembers what you deleted.
JavaScript
const items = [1, 2, 3];
// console.log('debugging noise');
console.log(items.length);Output
3
What to write
The code already says what it does. A comment earns its place when it says why, and the reason is not obvious from the lines themselves.
JavaScript
// Bad: repeats the code.
// Add one to the count.
count = count + 1;
// Good: explains a decision.
// The API rejects a page size above 50, so pull the rest in a second call.
const pageSize = 50;Tip
If a comment is needed to explain what a line does, a clearer name usually removes the need for the comment.
Comments go stale
A comment is not checked by anything, so it can quietly become a lie as the code around it changes. That is an argument for fewer, better placed comments rather than none.
Test yourself
2 questionsWhat makes a comment worth writing?
Show the answer
It explains why, not what The code already states what happens. The reasoning behind it is the part that is otherwise lost.
What is the risk with comments that no tool checks?
Show the answer
They drift out of date as the code changes A stale comment is worse than none, because it is trusted.
Variables
Names that point at values, and how to choose between const and let.