JavaScript comments explain code for people and are ignored by the JavaScript engine. Use // for a single-line comment and /* ... */ for a block comment that can span multiple lines.
Basic syntax:
// Single-line comment
const name = "plus2net";
/*
Block comment
across multiple lines
*/
console.log(name);
Everything after // on that line is treated as a comment, unless those characters are inside a string or another token where they have a different meaning.
// Store the initial score
let score = 0;
// Increase it after a correct answer
score += 1;
A short comment can follow a statement. Use this sparingly; if the explanation is long, put it on its own line.
const timeout = 5000; // milliseconds
const retries = 3; // maximum retry attempts
Block comments start with /* and end with */. They can span several lines.
/*
Calculate the final amount after discount.
The percentage is supplied as a whole number.
*/
function applyDiscount(price, percent) {
return price * (1 - percent / 100);
}
No. Normal JavaScript block comments do not nest. The first */ closes the comment.
/* Outer comment
/* Do not start another block comment here */
// The outer comment has already been closed above.
*/
// lines when you need commentary that might otherwise contain /* ... */ sequences.Comments can temporarily prevent a small piece of code from running while debugging, but version control is a better long-term record than leaving large amounts of dead code in production files.
const total = 25;
// console.log("Temporary diagnostic:", total);
console.log(total);
JavaScript itself treats a documentation-style block such as /** ... */ as an ordinary comment. Tools such as JSDoc and editors can interpret structured tags inside it.
/**
* Add two numbers.
* @param {number} a First number.
* @param {number} b Second number.
* @returns {number} Sum of a and b.
*/
function add(a, b) {
return a + b;
}
Use documentation comments where they help consumers understand a reusable API; do not document every obvious line.
Use JavaScript comment syntax inside JavaScript. Do not wrap modern scripts in the old HTML-comment pattern <!-- ... //-->. That pattern belonged to very old browser compatibility techniques and should not be copied into current code.
/* ... */ comments.Continue with adding JavaScript to HTML, variables, and functions.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Francis | 08-04-2010 |
| I really loved this website guys. | |