JavaScript Comments
Comments are notes in your code that JavaScript ignores completely. They explain why the code does something, temporarily switch code off, and leave hints for other developers — including you, six months from now.
Single-line comments
Everything after // until the end of the line is a comment. It can stand on its own line or follow code:
// Calculate the price including 20% VAT
const net = 50;
const gross = net * 1.2; // 1.2 = 100% + 20%
console.log(gross);60
Multi-line comments
A comment that starts with /* continues until */, across as many lines as you like:
/*
Shipping rules:
- orders of 100 or more ship free
- everything else costs 4.99
*/
const orderTotal = 120;
const shipping = orderTotal >= 100 ? 0 : 4.99;
console.log("Shipping:", shipping);Shipping: 0
Block comments can also sit in the middle of a line: const rate = /* per hour */ 25;. They cannot be nested — the first */ always closes the comment.
Commenting out code
Turning code into a comment is a quick way to disable it while you experiment or debug:
console.log("Step 1");
// console.log("Step 2 is skipped for now");
console.log("Step 3");Step 1
Step 3
Tip: Most editors toggle comments on the selected lines with Ctrl+/ (Cmd+/ on a Mac).
Documentation comments (JSDoc)
A block comment that starts with /** just before a function is a JSDoc comment. Editors read it to show tooltips and to check types, and tools can turn it into documentation:
/**
* Returns the area of a rectangle.
* @param {number} width - width in metres
* @param {number} height - height in metres
* @returns {number} the area in square metres
*/
function area(width, height) {
return width * height;
}
console.log(area(4, 2.5));10
Writing good comments
| Do | Don't |
|---|---|
Explain why: // Retry: the API sometimes times out |
Repeat what: // add 1 to i above i++ |
| Document surprising rules and edge cases | Leave large blocks of dead, commented-out code |
| Keep comments up to date when code changes | Use comments to excuse confusing names — rename instead |
Use // TODO: for known, tracked follow-ups |
Write jokes or secrets (comments ship to every browser!) |
Note: JavaScript sent to a browser is public. Anyone can open the developer tools and read your comments, so never put passwords or API keys in them.
Test yourself
Which syntax starts a single-line comment?
- #
- <!--
- //
- --
How does a multi-line comment end?
*///-->- At the end of the line
What is a /** ... */ comment above a function usually used for?
- Disabling the function
- JSDoc documentation and editor hints
- Making the function private
- Running the function at load time