There are three sticky notes on the drawers in the storeroom of Raka's T-Shirt Shop. The first says "Drawer". Useless, everyone can see it's a drawer. The second says "This drawer sticks, lift it a little before pulling". Useful, because you can't see that from the drawer. The third says "contents: black T-shirts", when it now holds caps. The third note is the worst kind: a note that lies misleads more than no note at all.
Comments in code, such as the text after //, work like those sticky notes, and the drawer is the code. Some comments only repeat what you can already see, like the first note. Some tell you something you can't see, like the second note. Some no longer match the code, like the third note. A good comment explains why, not what. What the code does is already written in the code. What you can't see is the reason.
The computer skips comments
Here's the checkout function of Raka's T-Shirt Shop with a comment on almost every line:
const VOUCHER_DISCOUNT = 0.1; // discount 0.1
const FREE_SHIPPING_MIN = 200; // free shipping from 200
const SHIPPING_FEE = 15; // shipping 15
function calculateTotal(cart, voucherCode) {
let total = 0; // total starts at 0
// loop over every item
for (const item of cart) {
total += item.price * item.qty; // add price times qty
}
// if the voucher is SAVE10, take off 10%
if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
// if the total is below 200, add shipping
if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
return 'Total: $' + total.toFixed(2); // return the total
}
There are nine comments, and every one only repeats the code in English. If you delete them all, the four carts in the first lesson's Lab still give Total: $220.50, $245.00, $90.00, $204.00, exactly the same. The computer skips everything after //. Comments are only for people. So the question for each comment is: does it tell a person something the code doesn't already say?
Comments that repeat the code go stale
Raka raises the free-shipping minimum (the threshold where shipping becomes free). The developer only changes the number in the constant:
const FREE_SHIPPING_MIN = 250; // free shipping from 200
The comment still says 200. It is now stale: it no longer matches the code, like the note "contents: black T-shirts" on the drawer. Guess first: for cart A with no voucher ($245), what total do the comments promise, and what does the code charge?
Two comments now lie: this one, and "if the total is below 200, add shipping" inside the function. A reader who trusts the comments thinks cart A with no voucher ($245) gets free shipping, so the total is Total: $245.00. The code charges Total: $260.00, because $245 is below $250. No error, just two sources that disagree. This is exactly the duplication problem from the DRY lesson: a number written in a comment is a second copy of the constant, and a second copy is easy to forget to update.
Comments that explain why
Here is the same version, with two comments that say something you can't read from the code:
const VOUCHER_DISCOUNT = 0.1;
// Raka's decision (March meeting): the shop pays the shipping when the order
// is big enough to cover the delivery cost. Ask Raka before changing it.
const FREE_SHIPPING_MIN = 200;
const SHIPPING_FEE = 15;
function calculateTotal(cart, voucherCode) {
let total = 0;
for (const item of cart) {
total += item.price * item.qty;
}
if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
// Shipping is checked AFTER the voucher: the threshold counts the money the
// buyer really pays. Cart D in the tests guards this order.
if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
return 'Total: $' + total.toFixed(2);
}
- The first comment answers "why is there a minimum, and who decided it". The code can only tell you the number.
- The second comment protects the order of the steps. Without it, a teammate who "tidies" the code by moving the shipping check above the voucher check makes cart D come out as
Total: $189.00instead of$204.00. - No minimum is copied into a comment. So when the minimum rises to $250, no comment becomes a lie.
Other things worth a comment:
- a workaround (a way around a problem) for a limit outside your code, such as a browser feature Safari doesn't support:
// Workaround: Safari does not support IntersectionObserver v2; - the reason behind a rule or regulation;
- warnings, like
// Deletes data permanently, cannot be undone.
Before writing a comment, try renaming
A comment that explains what is usually a sign of an unclear name:
const d = 86400000; // milliseconds in a day
const MS_PER_DAY = 86400000;
The second line needs no comment, because its name already says what it holds. The same goes for functions: a getData() with a three-line comment is better renamed to a name that explains itself.
Old code that's been commented out (turned into a comment so it doesn't run) "just in case" should simply be deleted. Git (a program that records the history of changes to code) already keeps its history. A TODO marker (a note about work that isn't finished) is fine, as long as it has context: who, when, and why.
Exercise: login session
In the exercise, isSessionValid(lastActivity, now) is full of comments that repeat the code, and the number 3600000 has no name:
- Delete the comments that repeat the code, including
// return the comparison result. - Move
3600000intoconst SESSION_TIMEOUT_MS = 3600000;(3,600,000 milliseconds = 1 hour), and use the constant in the function. Add a comment that says why: a security policy, inactive sessions expire after 1 hour. - Add
// TODO: move to env configright aboveconst API_KEY, which already exists and stays.
The output stays true then false. The function is also tested on its own: isSessionValid(0, 3600001) must be false (more than one hour has passed), and isSessionValid(3600000, 3600001) must be true. What's compared is the difference now - lastActivity: the time now minus the time of the last activity.
⚠️ When does a comment do harm?
- Comments that repeat the code.
total += ... // add price times qtyonly adds a line. Delete it. - Copying numbers into comments.
// free shipping from 200becomes a lie as soon as the constant changes. Write the reason, not the number. - A comment instead of a name. If you need a comment to explain
d, rename it toMS_PER_DAY. - Keeping old code as a comment. Git already keeps it. Delete it.
- In the exercise, comparing
nowalone.now < SESSION_TIMEOUT_MSgives the right results for the exercise's twoconsole.loglines, but the wrong one forisSessionValid(3600000, 3600001). Compare the difference.
TL;DR: A comment is text in code that the computer skips, such as the text after //. A good comment explains why, not what. Because the computer skips it, the question is: does a comment tell a person something the code doesn't already say? Nine comments that repeat the checkout function's code change no result. As soon as the free-shipping minimum rises to $250, the comments that copied the number 200 become lies. Cart A with no voucher ($245) ships "free" according to the comment, but costs Total: $260.00 according to the code. Useful comments keep the reason (Raka's decision on the free-shipping minimum, why shipping is checked after the voucher), workarounds (ways around a limit outside your code), rules and warnings. Delete comments that only explain what's already obvious from the code, try renaming before you comment, and delete commented-out code (code turned into a comment). In the exercise: delete the comments that repeat the code, make SESSION_TIMEOUT_MS = 3600000 with a comment about the 1-hour policy, add // TODO: move to env config above API_KEY, and the output stays true then false.
⚡ The computer skips comments
Write:
for (const item of cart) {
total += item.price * item.qty; // add price times qty
}
Meaning: A comment is text after //, which the computer skips. The comment on this line only repeats the code, so it tells nobody anything. The checkout function of Raka's T-Shirt Shop has nine comments that repeat the code. Delete them all and the four carts in the first lesson's Lab still give the same results. A good comment explains why, not what.
⚡ A number in a comment goes stale
Write:
const FREE_SHIPPING_MIN = 250; // free shipping from 200
Guess first: Raka raises the free-shipping minimum from $200 to $250, but nobody changes the comment. Cart A with no voucher is $245 of shopping, and shipping costs $15. What total does the comment promise, and what does the code charge?
The comment says $245 already ships free, so Total: $245.00. The code charges Total: $260.00, because $245 is below $250.
Meaning: That comment is stale: it no longer matches the code. A number written in a comment is a second copy of the constant FREE_SHIPPING_MIN, and a second copy is easy to forget to update. Write the reason, not the number.
⚡ Comments that explain why
Write:
// Shipping is checked AFTER the voucher: the threshold counts the money the
// buyer really pays. Cart D in the tests guards this order.
if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
Meaning: The code can only show what happens. The comment above keeps the reason: why shipping is checked after the voucher. Reasons, warnings, and workarounds (ways around a problem) for a limit outside your code, such as // Workaround: Safari does not support IntersectionObserver v2, are what deserve a comment.
⚡ Try renaming first
Write:
const d = 86400000; // milliseconds in a day
const MS_PER_DAY = 86400000;
Meaning: A comment that explains what is usually a sign of an unclear name. MS_PER_DAY (milliseconds per day) already says what it holds, so the second line needs no comment. Old code that's been commented out (turned into a comment so it doesn't run) should just be deleted, because git, a program that records the history of code, already keeps it.