JavaScript comments are often used to explain about the JavaScript code, to make the code easy to understand, especially when dealing with complex manner.
Advantages of JavaScript Comments
Avoid unnecessary code being executed
JavaScript comments also help to prevent unnecessary code being executed. Sometimes, we have found an alternative solution to that is better and we would like to test it out before a stable version new alternative solution released. We might temporarily comment out the old solution in case we need them in future and test the new and better alternative solution.
Easy to testing and debugging the code
JavaScript comments help to test to code easier by comment out the code and find the issues, errors and bugs.
Two Types of JavaScript Comment
There are two types of comment in JavaScript:
- Single Line Comment
- Multi Line Comment
Single Line Comment
To add single line comment, just add two forward slash //
before the code or text. Anything within the same line after the //
will be treated as JavaScript comment and it would not be executed.
// This is a single line comment
console.log("Hello World!");
The comment can be added in the same line even after the code. Make sure add //
before writing it as a comment.
var a = 10; // This is a comment
var b = 15; // This won't execute var c = 20;
Multi Line Comment
To add multi line comment, it starts from /*
and */
. Anything in between the /*
and */
will be treated as JavaScript comment and it would not be executed.
/* Multi Line Comment
The Second Line
The Third Line Comment */
console.log("Hello World!");