JavaScript Comments
About JavaScript Comments
In JavaScript, a comment is a piece of text in code that is not executed when the code is executed.
Comments are used to provide explanations, and keep documentation, or notes within the code for future reference and code understanding.
Comments are also useful for temporarily disabling code during debugging.
JavaScript supports two types of comments: single-line comments and multi-line comments.
Single-line Comment in JavaScript
In JavaScript, a single-line comment is created just adding two forward slashes (//) at the beginning of the line as demostrated in the following example:
Output of the above example
Greeting from JS tutorial!
The output does not contain the commented lines as they were ignored by the JavaScript engine.
Explanation of code
-
// This is a single-line comment: This is a single-line comment in JavaScript. Two forward slashes (//) are added at the beginning of the line to create a comment. -
let message = "Greeting from JS tutorial!";: Here the variable 'message' is initialized with a string value "Greeting from JS tutorial!". -
// This is also a single-line comment: This is another example of single-line comment in JavaScript. -
console.log(message);: In the line, 'console.log()' method prints the message in the web console.
Multi-line Comment in JavaScript
In JavaScript, anything between /* and */ is treated as multi-line comment as demostrated in the following example:
Output of the above example
Greeting from JS tutorial!
The output does not contain the commented lines as they were ignored by the JavaScript engine.
Explanation of code
-
/* This is an example of: The lines are commented using
multi-line comment
in JavaScript. *//*and*/at the begining and end of the lines. -
let message = "Greeting from JS tutorial!";: Here the variable 'message' is initialized with a string value "Greeting from JS tutorial!". -
console.log(message);: In the line, 'console.log()' method prints the message in the web console.
JavaScript Compiler For Live Practice
Practice the above JavaScript code in the following JavaScript Compiler. Create more JavaScript comments in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.
JavaScript Compiler