×

Javascript comment

Introduction

In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments are of no use to the computer, they are extremely important for human readers. Programmers use comments to provide suggestions, information, or warnings about the code.

Comment functions in JavaScript, similar to all other programming languages: The JavaScript engine will ignore comments entirely. Comments are ways for developers to comment on their code so that complex sections have additional background information. This aids not only their memory of the area but also that of other team members.

Though suggestions or explanations can be a limited application of comments, their principal purpose is for testing and debugging. Comments can halt the execution at certain lines, segments, or blocks of code, thereby aiding in finding bugs. Nevertheless, testers need to use comments carefully because improper use can lead to messes, which are discussed further in the latter sections of this article.

Types of JavaScript Comments (Description, Syntax, & Example)

This chapter discusses how to include comments in JavaScript code. Having discussed the basics of JavaScript comments, here are the approaches of including comments in JavaScript code. There are two major types of comments in JavaScript:

  1. Single-line comment
  2. Multi-line comment

Single-line Comment

As its name suggests, a single-line comment is intended to cause the compiler to stop the execution of only one line. To begin a single-line comment, one uses double forward slashes without any intervening spaces (//). One does not need to indicate the end of the single-line comment since the editor will automatically know the end when the line ends.

Syntax:

expression1 // expression2 or comment

expression3

In the syntax given above, expression 1 is that which could optionally occur before the start of the comment and will be executed. On the other hand, the expression after the two forward slashes, known as expression 2 will not be executed. Moreover, expression 3 sits in the next line and hence, it will be executed.

To elucidate the behavior of a single-line comment, let us take the following example:

Example:

In this instance, we will compose three expressions and incorporate a single-line comment to observe its operation.

Code:

console.log("expression_1") // console.log("expression_2")

console.log("expression_3")

Output

JavaScript Comment

In the above code, syntax has been applied, and variables expression_1 and expression_3 have been logged while expression_2 is commented; therefore, it will not be executed as an expression.

Multi-line Comment

Multi-line comments are the advanced type of single line comments. Here, execution may be suspended on multiple lines or even a block of code. A multi-line comment is invoked by using forward slash (/) followed by an asterisk (*) without any white spaces in between the two (*). It should be noted that an asterisk (*) followed by a forward slash (/) is used without spaces to indicate the end of a multi-line comment (*).

In contrast, Single-line comments do not need an explicit ending because the editor automatically recognizes the end of the line.

Syntax:

expression_1 /* expression_2 or comment

expression_4 

……

……

……

expression_n */ expression_(n+1)

expression_(n+2)

In the above syntax, expression_1 is the expression that either may or may not appear before the initialization of the comment, and it gets executed. The expressions lying between the pair of forward slashes and asterisks, and those lying between the pair of asterisks and forward slashes, namely from expression_2 to expression_n, do not get executed. Furthermore, the expression_(n+1) is present in the same line but after the end of the comment statement and hence will get executed along with expression_(n+2).

Example

Now let us look at the usage of the multi-line comment.

Code

console.log("expression_1") /* console.log("expression_2")

console.log("expression_2")

console.log("expression_3")

console.log("expression_4")

console.log("expression_5")*/ console.log("expression_6")

console.log("expression_7")

Output

JavaScript Comment

Explanation

In the above code, we have used the above syntax and printed the values of expression_1, expression_6 and expression_7 as other expression are not evaluated because of presence of a multi-line comment.

Using comments to stop execution

As mentioned above, the greatest use for comments is during testing or debugging phases of a program. In debugging, one is usually interested in knowing at which point exactly a bug takes place, thus knowing that some part of the code has nothing to do with the other and is error-free. Alternatively, we can opt to go back to that portion later, so we can comment it out and focus on a smaller chunk. Commenting out a particular portion of the code enables us to keep parts of the code for future use without having to delete them. Now, let us look at three different commenting styles to avoid the execution of a function.

Commenting Out Function Calls

A function is generally defined as a block of code that accepts certain predefined parameters and may return a value upon its invocation through a function call. If the function call is commented out, the associated function will not be invoked or processed.

Example

We shall create a function and an expression to call that function as well as offer commentary about that here.

Code

function add(a,b){

    return a+b;

}

//var sum = add(3,4);

Output

JavaScript Comment

Explanation

As indicated in the following code we create a function "add". But then, above the calling expression, there were comments therefore nothing is evaluated with this example. Functions come in two kinds: one that does not return a value, which generally is declared as having a return type of void, and one that returns a value, such as a string or an object. Now let's examine how to comment on the bodies of these functions:

Commenting Out Function Bodies — Functions Without Return Values

If the entire function, including its declaration, name, and parameters, is commented out, the compiler will ignore the entire code. Therefore, if the function call expression is left uncommented, an error will be reported stating that the function is undeclared.

On the other hand, if only the body of the function is commented out, the compiler will still check the syntax of the function, and there will be no issues with the function call.

Example

Let us write a code snippet to declare a function and subsequently comment out its body using multi-line comments.

Code

function add(a,b){

    /*

    console.log(a+b);

    */

}

add(3,4);

Output

JavaScript Comment

Explanation

In the code below, a function that does not return any output has been defined and its implementation commented out. Although the function is called, no output will appear in the console because of the multi-line comment that surrounds the body of the function.

Commenting Out Function Bodies — With Return Values

Generally, it is not a good idea to comment out the body of a function intended to return a value as it comments out the return statement too. As a result, the function will return an undefined value, and that could potentially create problems for the tester unless well handled. A possible approach to handling this would be to comment out the function calls.

Example

We will write a code block that will declare a function to which we expect it to return a certain value; later, we'll add multi-line comments to describe the implementation of that function.

Code

function add(a,b){

    /*

    return a + b;

    */

}

var sum = add(3,4);

console.log(sum);

Output

JavaScript Comment

Explanation

In the given code, a function has been declared that is supposed to return something. Its body is commented in JavaScript using the multi-line comment. The invocation of the function displays the returned value, which is undefined as there is no return statement in the code.

Advantages of JavaScript Comments

JavaScript comments benefit programmers in so many ways. Here are a few benefits from the use of comments:

  1. Adding comments makes the code more readable and understandable as it gives further explanation about what concepts are used.
  2. Comments help a team of people collaborate with each other; thus, a person can understand code that is hard to understand by others, but that is if appropriate comments are available.
  3. For a debugger, JavaScript comments are really useful; comments in certain areas of code make the execution stop, and one can debug that piece of code successfully.
  4. Use comments so that programmers don't have to delete parts of the code or copy them into another file when they are not sure whether they should delete it.

Writing good JavaScript comments

Comments are essential for programmers in order to improve code readability. However, in order to do so effectively, it is very important to do it in a proper manner. Here are some guidelines:

  1. Comments must be used to explain or set the background of a particular portion of code and should be very well expressed such that others would understand what functionality that portion serves.
  2. There are situations where multi-line comments are needed, and then there are others where single-line comments would suffice. Both need to be applied in moderation.
  3. Single-line comments are to be preferred wherever possible; where the comment is large, it should be split across multiple lines and a multi-line comment format should be employed.
  4. For comments that can be written immediately after an expression, a single-line comment is best placed following the expression rather than preceding it.

Conclusion

1. Programming languages use comments to add meaningful messages to the program that aren't interpreted by compilers or interpreters.

2. Programmers can add more information on complex steps.

3. JavaScript has two ways of commenting and is classified into two types. Those are

  • Single-line comment (// comment)
  • Multi-line comment (/* comment */)

5. The double forward slashes, not separated by spaces, are used to initiate a single-line comment without the need to mark the end of the single-line comment.

6. Starting from the multi-line comment, a single forward slash (/) and then the asterisk (*) without any space is used; this requires having an asterisk (*) followed by a single forward slash (/) without any space at the end of the multi-line comment as (* /).

7. For debugging, comments in JavaScript are very useful since they enable the developer to comment out certain sections of code and stop the execution of the code for easier debugging.


Related Topics

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

JavaScript Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.

JavaScript Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

Javascript Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.