Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

Commenting in JavaScript

When writing code, it is very important to leave notes for anyone that might read your code in the future. There are two ways to write notes in JavaScript.
Single-Line Comment
Here is an example of a single-line comment (using //):
//the variable below stores the username
var name = 'Jon';
Multi-Line Comment
Here's an example of a comment that spans multiple lines:
/* the variable below
    stores the
    username
*/
var name = 'Jon';
Which one should I use?
I personally use the single-line commenting style most of the time. Let me explain why.

Consider the following code:
//I am declaring a variable named lastName
var lastName = 'Smith';

//The below code takes the last name
//and compares it to the value 'Smith'
if(lastName == 'Smith') {
    alert('Hi');
}
If I want to comment out this whole section temporarily (e.g. for testing), it's easy to use the multi-line commenting syntax:
/*

//I am declaring a variable named lastName
var lastName = 'Smith';

//The below code takes the last name
//and compares it to the value 'Smith'
if(lastName == 'Smith') {
    alert('Hi');
}

*/
Notice the gray color (this code will not be run).

Now, consider if I hadn't used single-line comments:
/*I am declaring a variable named lastName*/
var lastName = 'Smith';

/*The below code takes the last name
   and compares it to the value 'Smith'*/
if(lastName == 'Smith') {
    alert('Hi');
}
If I want to quickly comment out this section, it won't let me wrap multi-line comments with a multi-line comment:
/*

/*I am declaring a variable named lastName*/
var lastName = 'Smith';

/*The below code takes the last name
   and compares it to the value 'Smith'*/
if(lastName == 'Smith') {
    alert('Hi');
}

*/
And that's why I prefer to use single-line comments.
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License