Skip to main content
0 reactions

How to Write a Comment in JavaScript

Card titled Comments in JavaScript, labelled JavaScript basics, with four ticked lines: // for one line, /* */ for several lines, the switched-off Goodbye line skipped, and the output Hello and Done.

A comment is a note in your code that JavaScript skips when it runs. Use it to say what the code does, or to switch a line off without deleting it. JavaScript has two kinds: // for the rest of one line, and /* */ around any number of lines.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
// a comment to the end of the line

/* a comment that can
   cover several lines */
  • //: everything after it, to the end of the line, is a comment. It can follow code on the same line.
  • /* and */: everything between them is a comment, across any number of lines.

See Comments (opens in a new tab) in MDN’s Lexical grammar page.

Prerequisites

The Example

A file named greet.js with both kinds of comment: a note on its own line, a switched-off line inside /* */, and a note after code.

Step 1: Write the Code

greet.jsJavaScript
// Greet the reader
console.log('Hello');

/* This line is switched off:
console.log('Goodbye');
*/
console.log('Done'); // the rest of this line is a comment

Step 2: Run It

TerminalBash
node greet.js
OutputPlain text
Hello
Done

Only Hello and Done are printed. The Goodbye line sits inside /* */, so it never runs, and the note after the last line is skipped too.

Common Mistakes

MistakeWhat happensDo this instead
Starting a comment with #SyntaxError: Invalid or unexpected token, and the file doesn’t runUse //. # starts comments in other languages, such as YAML and Python
Putting a /* */ comment inside another oneThe first */ ends the whole comment, so the text after it is read as code and gives a SyntaxErrorUse // on each line, or one /* */ only

FAQ

Can a comment go after code on the same line?

Yes, with //: in console.log('Done'); // note, everything after // is skipped.

Conclusion

Write // for a one-line note, and /* */ around several lines. JavaScript runs everything else.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments