Skip to content

JavaScript Comments

JavaScript comments are used to add explanatory notes to your code, making it more understandable for yourself and others.

Comments are ignored by the JavaScript engine and do not affect the execution of the program. They can also be used to temporarily disable lines of code for testing purposes.

Single-line comments start with //.

Any text from // to the end of the current line is treated as a comment and will be ignored by JavaScript.

Example: Using single-line comments to explain code:

// Get the heading element and change its text content
const myHeading = document.getElementById("myH");
myHeading.textContent = "My Updated Page Title";
// Get the paragraph element and update its content
const myParagraph = document.getElementById("myP");
myParagraph.textContent = "This is my updated first paragraph.";

Example: Using single-line comments at the end of lines:

let x = 5; // Declare variable x and assign it the value 5
let y = x + 2; // Declare variable y and assign it the value of x + 2 (which is 7)

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript, regardless of how many lines it spans.

Example: Using a multi-line comment (a comment block) to explain a section of code:

/*
The following code block performs two actions:
1. It retrieves the HTML element with the ID 'myH' and updates its content.
2. It retrieves the HTML element with the ID 'myP' and updates its content.
This is useful for more detailed explanations.
*/
document.getElementById("myH").innerHTML = "My First Page Revisted";
document.getElementById("myP").innerHTML = "My first paragraph, updated again.";
While both comment types are useful, single-line comments (//) are often preferred for quick, concise explanations, while multi-line comments (/* ... */) are good for longer descriptions or for temporarily disabling larger blocks of code. JSDoc comments, which use a /** ... */ syntax, are a special form of multi-line comment used for generating documentation.

Using Comments to Prevent Execution (Debugging)

Section titled “Using Comments to Prevent Execution (Debugging)”

Commenting out code is a common technique during development and debugging to temporarily prevent certain lines or blocks of code from running, without deleting them.

Example: Using // to prevent execution of one line:

// document.getElementById("myH").innerHTML = "This line is commented out.";
document.getElementById("myP").innerHTML = "This paragraph will be updated.";

Example: Using a multi-line comment to prevent execution of multiple lines:

/*
console.log("This will not be logged.");
const importantValue = 42;
if (importantValue > 10) {
console.log("This block is also commented out.");
}
*/
console.log("This line will execute.");

This allows you to isolate parts of your code to find errors or test different approaches.