Course Content
Introduction to JavaScript
Introduction to JavaScript
Comments
Sometimes, you may need to prevent a specific part of your code from executing. Deleting the entire code isn't convenient if you want to test a separate section later. There are various scenarios where you may need to temporarily halt the execution of a non-working part of your code. In such cases, comments come to your rescue.
Note
Comments provide a syntax for hiding sections of your code from the interpreter or compiler. They are also valuable for documenting code for other developers.
Single-line Comments
Single-line comments block the entire line of code, ensuring that the code above and below them is executed. The syntax for single-line comments is straightforward: you need to add //
before the code on the line you wish to comment out:
console.log("Line 1"); // console.log("Line 2"); console.log("Line 3");
The example above shows that the comment //
blocks the second code line, which is not executed.
We can also use single-line comments to block multiple lines of code in a row:
console.log("Line 1"); console.log("Line 2"); // console.log("Line 3"); // console.log("Line 4"); console.log("Line 5");
Also, we can add the comment at the end of the line.
console.log("Part 1.1"); console.log("Part 1.2"); console.log("Part 2.1"); // console.log("Part 2.2") console.log("Part 3.1"); console.log("Part 3.2");
Multi-line Comments
Consider a situation with a large code block, 299 lines long. Commenting each line individually would be time-consuming. That's where multi-line comments come in handy.
Multi-line comments start with /*
and end with */
. Any code enclosed within them is commented out:
console.log("Line 1"); console.log("Line 2"); /* console.log("Line 4"); console.log("Line 5"); console.log("Line 6"); console.log("Line 7"); console.log("Line 8"); console.log("Line 9"); */ console.log("Line 11");
In the example above, we can see that code line from 3 to 10 hasn't been executed.
We can use multi-line comments to comment a part of the line:
console.log("Part 1", /* "Part 2", */ "Part 3");
/* console.log("Part 1"); */ console.log("Part 2");
Thanks for your feedback!