×

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

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 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 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 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.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 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 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 Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 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.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 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 Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes 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.