Monday, June 17, 2019

JavaScript Comments

JavaScript Comments

Have you ever written a script or a program in the past only to look at it six months later with no idea what's going on in the code? You probably forgot to do what all programmers tend to forget to do: write comments

When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code, they will also be able to understand the code (hopefully)!

Another great thing about comments is the ability for comments to remove bits of code from execution when you are debugging your scripts. This lesson will teach you how to create two types of comments in JavaScript: single line comments and multi-line comments.

Creating Single Line Comments

To create a single line comment in JavaScript, you place two slashes "//" in front of the code or text you wish to have the JavaScript interpreter ignore. When you place these two slashes, all text to the right of them will be ignored, until the next line.

These types of comments are great for commenting out single lines of code and writing small notes.

JavaScript Code:
<script type="text/javascript">
<!--
// This is a single line JavaScript comment

document.write("I have comments in my JavaScript code!");
//document.write("You can't see this!");
//-->
</script>


Display:

I have comments in my JavaScript code!
Each line of code that is colored red is commented out and will not be interpreted by the JavaScript engine.
Creating Multi-line Comments

Although a single line comment is quite useful, it can sometimes be burdensome to use when disabling long segments of code or inserting long-winded comments. For this large comments you can use JavaScript's multi-line comment that begins with /* and ends with */.

JavaScript Code:

<script type="text/javascript">
<!--
document.write("I have multi-line comments!");
/*document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");
document.write("You can't see this!");*/
//-->
</script>


Display:

I have multi-line comments!
Quite often text editors have the ability to comment out many lines of code with a simple key stroke or option in the menu. If you are using a specialized text editor for programming, be sure that you check and see if it has an option to easily comment out many lines of code!