Table of content:

A JavaScript comment is a powerful programming construct to explain complex code blocks, what they do, and why they were implemented in a particular way. As systems and websites evolve, Developers always end up writing complex code. Code written this way might make complete sense to the original author or Developer, but might not be obvious to a Developer new to the team looking at the code for the very first time, or even to the author’s future self. In such cases, comments are a very powerful tool to explain the thought process and decisions made while writing a block of code.

A Developer can write comments in JavaScript — both single-line comments for a quick explanation and multi-line comments for a detailed explanation or formal documentation. Let’s take a look at JavaScript comments

JavaScript Single-Line Comment

Single-line comments are very useful for adding a quick comment or explanation over a line of code. In JavaScript, a single-line comment can be added by using two forward slashes //. Below are some examples of single-line comments in JavaScript code.

// This will output "Hello, World!" to the browser's console.
console.log("Hello, World!");

result = 3 + 7; // comments can also follow a statement like this

JavaScript Multi-Line Comment

Sometimes, a single line is not enough to document or explain why certain code is written in a particular way or what it does. This is when a JavaScript Developer will opt for writing comments across multiple lines (a JavaScript multi-line comment can also be referred to as block comments).

Multi-line comments in JavaScript code can be added by writing the comment between a forward slash followed by an asterisk /* and an asterisk followed by a forward slash */. Below are some examples of multi-line comments.

/* Add two numbers and
   Store the output in a variable called result.
   Also, print the output to the browser’s console
let result = 6 * 5;
console.log("Multiplication result is: ", result);

Using Code Comments to Prevent Execution

When testing your code, adding two forward slashes // in front of code lines will convert the code to a comment, rather than an executable line.

To prevent the execution of multiple lines, a comment block can be used.