How do you Comment Code in JavaScript?

Last updated on March 10, 2023

JavaScript allows you to write non-executable text called comments. The comments can be code explanations, instructions, logic steps, or pseudo-code. JavaScript comments can be used to prevent code execution for debugging purposes.

Prevent Code Execution

With comments, we can also prevent code to execute. In the below example, we commented on the commented line of code through the double forward slashes.

// Comment the code section
//document.getElementById("sum").value = z;

In this example, both lines are commented and the browser will ignore these lines. There are two types of comments single-line comments and multiline comments.

  • Single Line Comment
  • Multiline Comment

Single Line Comment

The single line comments start with a double forward slash (//) after this code all of the words will be commented and the browser will ignore the line.

Multiline Comment

Multiline code comment as know block comments in the javascript is very easy just start with a forward slash and static (/*) and end with (*/) it will comment the code block and the browser will ignore these lines to execute.

/*
The below code will set the 
page title and subtitle 
*/
document.getElementById("pageTitle").innerHTML = "Page Title";
document.getElementById("sub-title").innerHTML = "Sub Title";

In the above example we commented on the hint code which is starting with the forward-slash (/*) plus steric and then the content of the hint closes with the asteric and forward slash (*/) so all of the text between this will be ignored by the browsers.

Conclusion

This article demonstrates comments in JavaScript. JavaScript comments can be used for hints, explanations, and steps of logic, or prevent the specific code to execute with single-line or multiline- comments.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: JavaScript,