iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Comments

Comments document why, not what. Good code names what is happening; comments explain the WHY a future reader cannot derive.

Comments in practice

EXAMPLE
// 1. Single-line comment
const PORT = 3000;  // matches production reverse proxy

/*
 * 2. Multi-line comment
 * Use for longer explanations of WHY a decision was made.
 */

// 3. JSDoc - typed documentation
/**
 * Calculates the discount for a customer.
 * @param {number} total  - order total in cents
 * @param {'student'|'vip'|'none'} tier
 * @returns {number} discounted total in cents
 */
function discount(total, tier) {
  if (tier === 'student') return Math.round(total * 0.85);
  if (tier === 'vip')     return Math.round(total * 0.70);
  return total;
}


// 4. TODO / FIXME / HACK - tagged for tools to find
// TODO: replace with a real auth check once SSO is wired
// FIXME: handles negative amounts incorrectly
// HACK: forces a re-render to work around bug #1234


// 5. Type hints in plain JS (with VS Code)
/** @type {string[]} */
const tags = [];


// 6. NEVER comment what the code already says
// BAD
let i = 0;          // initialise i to zero
i++;                // increment i by one

// GOOD
// We start from 0 because IDs are 1-indexed and we count from the user's perspective
let displayIndex = 0;


// 7. Use comments to explain hidden constraints
// stripe rate-limits this endpoint to 100/sec; do not parallelise above 80
await stripe.charges.list({ limit: 100 });


// 8. Strip comments in production builds
// Most bundlers (Vite, esbuild) drop comments by default
// JSDoc survives if you use a documentation extractor


// 9. ESLint can enforce comment rules
// 'no-warning-comments': ['error', { terms: ['TODO', 'FIXME'] }]
// (in a release branch only - your default branch should have TODOs)


// 10. Type imports / triple-slash in TS files
/// <reference path='./types.d.ts' />

Why it matters

Comments explain why; names explain what. A comment that mirrors the code adds noise; a comment that captures a non-obvious constraint or a workaround for a real bug earns its keep for years.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Comments!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Wrap this label as a single-line JS comment.

Section: buttons

Test yourself

Q1. Single-line comment uses…
Q2. JSDoc comments add…
Q3. A good comment explains…

Discussion

Loading…