JS Comments
JavaScript Comments: Documenting Why Code Exists
JavaScript comments are notes inside source code that the engine completely ignores at runtime. Developers use comments to explain non-obvious business rules, document function parameters, and temporarily disable lines during debugging.
Single-Line, Multi-Line, and JSDoc Syntax
JavaScript supports three comment formats depending on how much context you need to share:
- Single-line comments (
//): Ignore everything from//to the end of that line. Ideal for brief notes or disabling one statement. - Multi-line block comments (
/* ... */): Ignore everything between/*and*/across one or more lines. - JSDoc comments (
/** ... */): Structured comments that describe function arguments and return types for IDE tooltips and automated docs.
/**
* Calculates shipping cost based on weight in kilograms.
* @param {number} weightKg - Package weight in kg.
* @returns {number} Shipping fee in USD.
*/
function getShippingFee(weightKg) {
// Free shipping applies to light promotional samples under 0.5 kg
if (weightKg < 0.5) {
return 0;
}
/* Base rate is $4 plus $1.50 per extra kilogram.
Keep this formula aligned with billing-service v2. */
return 4 + Math.ceil(weightKg) * 1.5;
}
console.log("Fee for 2.2kg:", getShippingFee(2.2));
Writing Useful Comments
Good code explains what happens through clear variable and function names. Good comments explain why a weird workaround or business threshold exists. Avoid restating the obvious like // increment counter by 1 above counter++.
Common Mistakes to Avoid
- Nesting block comments: Writing
/* outer /* inner */ outer */breaks because the first*/closes the entire comment block early. - Leaving stale comments behind: Updating code without updating its comment misleads future teammates who trust the note over the logic.
- Committing commented-out dead code: Delete unused functions instead of commenting them out; Git history already keeps every past version safely.
Frequently Asked Questions
Do JavaScript comments slow down my website?
Comments have zero impact during execution, though large comments increase file download size. Production bundlers like Vite and Webpack strip all comments automatically when minifying code.
When should I use JSDoc comments?
Add JSDoc blocks to shared utility functions, API helpers, and library exports. Editors like VS Code read JSDoc tags to show autocomplete hints without requiring TypeScript.
Is there a keyboard shortcut to comment lines quickly?
Yes, press Ctrl + / on Windows or Cmd + / on macOS in VS Code to toggle // comments on selected lines.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.