Comments are used to describe and explain javascript code and make it more readable. Comments are not executed unlike the code. The javascript interpreter, when it encounters any comments, ignores the comments and continues execution till the end of file.
Single line comments start with two forward slashes //
Any text or code from // to the end of the line, will be ignored by JavaScript interpreter and will not be executed.
Below example uses a single line comment on each line, to explain the code in the next line:
// Assign a value of 20 x = 20; // Now multiply x with 100 and save the result into x x *= 100;
Below example uses a single line comment at the end of each line, to explain the code:
x = 20; // Assign a value of 20 x *= 100; // Now multiply x with 100 and save the result into x
Multiple-line comments start with /* and end with */. Any code, text or even comments between /* and */ will be ignored by JavaScript. Below example uses a multi-line comment (a comment block) to explain the code:
/* My algorithm is described below: Assign a value of 20 to x. Then multiply x with 100 and save the result into x */ x = 20; x *= 100;
Comments can have code, text or even other comments. For example the below snippet has a single line comment inside a multiline comment.
/* My algorithm is described below: Assign a value of 25 to x. Then multiply x with 100 and save the result into x //x = 20; */ x = 25; x *= 100;
Sometimes, as a programmer you may need to comment out some of your code either temporarily or permanently so that you achieve different results.
//x = 20; x = 25; x *= 100;
In the above example, the first line of code which was working fine before, was commented out to have different initial value for x.
Many modern editors from IDEs such as Eclipse, Visual Studio 2015 provide a simple way to comment/uncomment a block of code using keyboard shortcuts. For example in Visual studio, you can highlight a block of lines and press Ctrl+k+c to comment the entire block. The reverse is also possible by a different shortcut. In visual studio, you can highlight a block which is already commented out and press Control key (Ctrl)+k+u to uncomment in one shot.