JavaScript Comments

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

In Javascript, single-line comments start with //. Any code written after // will be ignored by Javascript.

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

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


Hello Tech!

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

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


Computer science portal

Multi-line Comments

In Javascript, multi-line comments start with /* and end with */. Any text or code written between /* and */ will be ignored by JavaScript at the time of execution.

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

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


Multiline comment in javascript

JavaScript Comments to Prevent Execution

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

Example 1: 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.

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

Output: The sum is calculated but is only displayed once because the code to display the sum is written in a comment in the other line and will not be displayed.


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

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