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:
// 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?
- Explaining why. The code shows what you're doing. A good comment explains why you're doing it.
- Leaving reminders. Like
// TODO: make this work for negative numbers. - 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.
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.