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.
Here is an example of a single-line comment (using //):
//the variable below stores the username
var name = 'Jon';
Here's an example of a comment that spans multiple lines:
/* the variable below
stores the
username
*/
var name = 'Jon';
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.
Leave a comment