JavaScript Comments
Last Updated :
26 Jul, 2024
JavaScript comments help explain code, making it easier to understand. You can also use them to temporarily disable parts of your code. The JavaScript compiler ignores comments when running the code.
A single-line comment in JavaScript is denoted by two forward slashes (//),
Syntax:
// your comment here
Example 1: This example illustrates the single-line comment.
JavaScript
// A single line comment
console.log("Hello Geeks!");
Example 2: In this example, we will assign values to some variables and explain them with single-line comments.
JavaScript
// Declaring a variable and assign value to it
let geek = 'Computer science portal';
console.log(geek)
// Perform operation of addition of two numbers
let sum = 5 + 8
console.log(sum)
OutputComputer science portal
13
A multiline comment in JavaScript is a way to include comments that span multiple lines in the source code.
Syntax:
/*
This is a multiline comment
It can span multiple lines
*/
Example: This example illustrates the multi-line comment using /* … */
JavaScript
/* It is multi line comment.
It will not be displayed upon
execution of this code */
console.log("Multiline comment in javascript");
OutputMultiline comment in javascript
JavaScript Comments to Prevent Execution
We can use // or /*…*/ to change the JavaScript code execution using comments. JavaScript Comments are used to prevent code execution and are considered suitable for testing the code.
Example 1: JavaScript comments are used to prevent execution of selected code to locate problems of code or while testing new features. This example illustrates that commented code will never execute.
JavaScript
function add() {
let x = 10;
let y = 20;
let z = x + y;
// console.log(x + y);
console.log(z);
}
add();
Example 2: This example uses multi-line comments to prevent the execution of addition code and perform subtraction operations.
JavaScript
function sub() {
let x = 10;
let y = 20;
/* let z = x + y;
console.log(z); */
let z = x - y;
console.log(z);
}
sub();
JavaScript Comments – FAQs
What are comments in JavaScript?
Comments are non-executable parts of the code used for explanations, documentation, and debugging.
How do you write a single-line comment in JavaScript?
Use // at the beginning of the line.
How do you write a multi-line comment in JavaScript?
Enclose text with /* and */.
Can comments be nested in JavaScript?
No, nesting comments is not allowed and causes syntax errors.
Why are comments useful in JavaScript?
They enhance code readability, aid debugging, and document complex logic.
Can comments affect the performance of JavaScript code?
No, comments are ignored during execution but may increase file size.
Please Login to comment...