Open In App
Related Articles

JavaScript Comments

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

JavaScript comments are used to explain the code to make it more readable. It can be used to prevent the execution of a section of code if necessary. JavaScript comments are ignored while the compiler executes the code.

Single Line Comments

A single-line comment in JavaScript is denoted by two forward slashes (//),

Syntax:

// your comment here

Example 1: This example illustrates the single-line comment. 

Javascript

// A single line comment 
console.log("Hello Geeks!");

                    

Output
Hello Geeks!

Example 2: In this example, we will assign values to some variables and explain them with single-line comments.

Javascript

// Declaring a variable and assign value to it
let geek = 'Computer science portal';
console.log(geek)
 
// Perform operation of addition of two numbers
let sum = 5 + 8
console.log(sum)

                    

Output
Computer science portal
13

Multi-line Comments

A multiline comment in JavaScript is a way to include comments that span multiple lines in the source code.

Syntax:

/*    
This is a multiline comment
It can span multiple lines
*/

Example: This example illustrates the multi-line comment using /* … */ 

Javascript

/* It is multi line comment. 
It will not be displayed upon
execution of this code */ 
 
console.log("Multiline comment in javascript");

                    

Output
Multiline comment in javascript

JavaScript Comments to Prevent Execution

We can use // or /*…*/ to change the JavaScript code execution using comments. JavaScript Comments are used to prevent code execution and are considered suitable for testing the code.

Example 1: JavaScript comments are used to prevent execution of selected code to locate problems of code or while testing new features. This example illustrates that commented code will never execute. 

Javascript

function add() {
    let x = 10;
    let y = 20;
    let z = x + y;
    // console.log(x + y);
    console.log(z);
}
 
add();

                    

Output
30

Example 2: This example uses multi-line comments to prevent the execution of addition code and perform subtraction operations.

Javascript

function sub() {
    let x = 10;
    let y = 20;
    /* let z = x + y;
    console.log(z); */
 
    let z = x - y;
    console.log(z);
}
 
sub();

                    

Output
-10


Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads