JavaScript Tutorial – Comments

What is JavaScript Comments

JavaScript comments are not displayed in the browsers. You can use comments to explain your code, so your code is a lot more easier to read and maintain. JavaScript comments can also be used to stop a function or a piece of code from executing. This is extremely useful when you need to do a quick debug.

There are 2 common types of comments in JavaScript, single line comments and multi-line comments.

Single Line Comment

Single line comments start with // and all the text to the right will be ignored by the browsers. These types of comments are every useful when you need to do just a few lines of comments.

How to Use Single Line Comment in JavaScript


//this is an example of single line comment 
//browsers will ignore these comments 
document.write("Hello World!");

Multi-line Comment

Multi-line comments start with /* and end with */. Any text in between is treated as comments and will not be interpreted by the JavaScript.

How to Use Multi-line Comment in JavaScript


/*
This is an example of multi-line comment in JavaScript.
This may span multiple lines.
*/
document.write("Hello World!");

How to Stop JavaScript Execution With Comments

If you ever need to stop a few lines of JavaScript from executing, you can simply comment them out. You can either do this with single line comment or block comment.

This example uses single line comment, //, to prevent the execution of JavaScript


//document.write("stop JavaScript from executing with single line comment");

This example uses block comment, /* */, to prevent the execution of a block of JavaScript code


/*
document.write("stop JavaScript from executing with block comment");
document.write("This will not execute");
*/