JS Comments

JavaScript Comments

JavaScript comments are used to explain the purpose of your code and make it more readable. Comments are not executed as a part of the program; they are solely meant for human developers to understand the code better. The browser simply ignores them.

You can use comments for various purposes, such as:

Tip: A good developer always writes clear comments to explain the why behind complex code logic.

Learn how to declare variables to store data in our JS Variables tutorial.

Types of Comments in JavaScript

There are two common ways to write comments in JavaScript:

  1. Single-line comments
  2. Multi-line comments

1. Single-Line Comments in JavaScript

You can start a single-line comment with a double forward slash (//). Everything written after the // until the end of that specific line is treated as a comment.

Syntax:

// This is a single-line comment message

Single-Line Comment Example:

// Defining the first string
var string1 = "JavaScript";

// Defining the second string var string2 = "TypeScript";

// Printing the combined strings document.write(string1, " and ", string2);


2. Multi-Line Comments in JavaScript

The multi-line comment is extremely useful when you need to comment out multiple lines of code or write a longer, detailed explanation. You can write multi-line comments between the /* and */ symbols.

Syntax:

/* First line of the comment message
   The second line of the comment message */

Multi-Line Comment Example:

let result = addition(100, 200);
document.write("Result = " + result);  

/* This function accepts two values as parameters, adds them together, and returns the computed result */ function addition(a, b) { return a + b; }


3. Using Comments to Prevent Execution

In addition to providing information about the code, comments are frequently used during the debugging process to prevent the execution of a particular piece of code.

By commenting out a line or a block of code, you can test how your program runs without it, saving you the hassle of deleting and re-typing it later.

Preventing Execution Example:

var bool1 = true;
var a = 100;
var b = 200;

// The line below is commented out, so bool1 remains true // bool1 = false;

/* The block below is completely ignored by the browser: a = a + b; b = a - b; a = a - b; */

document.write("bool1 is: " + bool1 + "<br>"); // We can place a comment at the end of a line document.write("a = " + a + ", b = " + b);


Exercise

?

Which syntax is used to create a multi-line comment in JavaScript?