Once you start writing code, you’ll realize that not everything you write is meant to be executed by the program.
On top of that, your code will become difficult to understand, especially if you don’t follow naming conventions which we will discuss later. I can confirm that sometimes when I return to my code only after few hours later, I have a tough time to get everything I wrote.
For these reasons, it’s extremely useful to leave notes for yourself, other developers, but something that would be ignored by the program itself. That’s exactly what comments are good for. They can explain what the program is doing, leave instructions for yourself what to implement later, and any other useful annotations.
- A single-line comment
- A multi-line comment
A single-line comment is for a single line of annotation and it is denoted with two forward slashes
You can use it above the line of code:
//This code prints 5 to the console
Or you can use it after the line of code:
console.log(5); // This code prints 5 to the console
A multi-line comment is used for many lines of code and it is denoted with
/* at the beginning, and
*/ at the end of the comment:
This is all ignored by the computer
None of it will run
You can also use this syntax to comment something out in the middle of a line of code:
console.log(/*THIS IS IGNORED!*/5); // This still prints just 5
Copy the code above, paste it to your console and hit Enter.