Comments: Notes to Your Future Self

Kindergarten, page 7 of 9. A one-minute read.

Sometimes you want to write a note in your code that's meant for humans, not the computer. That's what comments are for. JavaScript completely ignores comments.

There are two kinds:

JavaScript
// This is a single-line comment. Everything after the two slashes is ignored.
console.log("Comments are ignored"); // You can put one at the end of a line, too.

/*
  This is a multi-line comment.
  It starts with slash-star and ends with star-slash.
  Great for longer explanations.
*/
console.log("See? Nothing else printed.");

It prints

Comments are ignored
See? Nothing else printed.

What are comments good for?

  1. Explaining why. The code shows what you're doing. A good comment explains why you're doing it.
  2. Leaving reminders. Like // TODO: make this work for negative numbers.
  3. Switching code off temporarily. Put // in front of a line and it stops running, without you having to delete it. Programmers call this commenting out code.
JavaScript
console.log("This line runs.");
// console.log("This line is taking a nap.");
console.log("This line runs too.");

It prints

This line runs.
This line runs too.
TipKeyboard shortcut

In VS Code, select some lines and press Ctrl + / (or Cmd + / on Mac) to comment them all out at once. Press it again to bring them back to life.

Watch outComments that say nothing

A comment like // print hello above console.log("hello") is just noise. The code already says that! Save your comments for things that aren't obvious from the code itself.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning