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
// 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
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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 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
node greet.js
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
| Mistake | What happens | Do this instead |
|---|---|---|
Starting a comment with # | SyntaxError: Invalid or unexpected token, and the file doesn’t run | Use //. # starts comments in other languages, such as YAML and Python |
Putting a /* */ comment inside another one | The first */ ends the whole comment, so the text after it is read as code and gives a SyntaxError | Use // 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
- Lexical grammar: Comments (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments