What Are JavaScript Comments?

By: Dusty Arlia
Published on September 25, 2012
Last Updated on Friday, July 17, 2015 at 11:43 PM
Total Updates: 7

When you are programming you will want to add comments to your code. Comments document the code's behavior. It can be easy to understand what the code is doing, but it can be difficult to understand WHY it is doing what it is doing. Adding a comment to your code will make it easier to understand when you have to read your code again later. It's also likely that someone else will be reading your code. The time you spend writing the code is short relative to the time you spend maintaining the code.

Using comments is just like taking notes on a complicated subject - you want to make something complex easier to understand.

Comments are not executed. When a JavaScript interpreter comes across a comment it ignores it. Comments are recognized by a certain string of characters that precedes them (and follows them if you use multiline comments). You can use single-line comments which start off with two forward slashes (//). And you can also use multiline comments which start with /* and end with */.

Here are two examples:

//this is a single-line comment
var i = 1;   //and this is a single-line comment

Program Name: Slideshow
Author: Dusty Arlia
Date: September 25, 2012
Description: The script automates the picture transitions.

This is an example of a multiline comment

But you could also go against their recommended use and do something like the following, which is also acceptable:

//This comment is spanning
//more than a single line

/*while this one is a single line*/