javascript Tutorial

JavaScript Comment

Learn more about one of the world’s most popular programming languages.

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 code that is complex. 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.

Web Developer can write comments in JavaScript — both single-line comments for 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 to add 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.

Code Example
// 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 asterisk /* and asterisk followed by a forward-slash */. Below are some examples of multi-line comments.

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

Using Code Comments to Prevent Execution

When testing your own 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.

Learn JavaScript Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required