JavaScript Comments

JavaScript comments explain code and make it more readable. Comments are completely ignored by the JavaScript engine and do not execute—they exist solely for developers to document, explain, and clarify code for themselves and others.

Comment Types

JavaScript supports two types of comments: single-line comments and multi-line comments. Single-line comments start with two forward slashes (//) and extend to the end of the line. Everything after // on that line is treated as a comment and ignored by the JavaScript engine. You can place single-line comments on their own line or at the end of a code line to explain that specific statement.

Multi-line comments (also called block comments) start with /* and end with */. Everything between these delimiters is treated as a comment, regardless of how many lines it spans. Multi-line comments are useful for longer explanations, documentation blocks, or temporarily disabling multiple lines of code. You can also use them for inline comments within a single line, though this is less common.

Comments serve multiple purposes in programming. Their primary use is to explain code and make it more readable and maintainable. Good comments explain the why behind decisions, clarify complex logic, document assumptions and constraints, warn about gotchas, and provide context that isn't obvious from the code itself. Comments help other developers (and your future self) understand your code quickly.

Comments are invaluable for temporarily disabling code during testing and debugging. By "commenting out" code, you can prevent it from executing without deleting it. This is useful when testing different approaches, isolating bugs, or checking if specific code is causing problems. Once you've finished testing, you can uncomment the code or remove it entirely if it's no longer needed.

Good comments explain why something is done, not what is being done. The code itself shows what is happening—comments should provide the reasoning, context, or explanation that code alone cannot convey. Avoid redundant comments like "// increment i" above "i++". Instead, write comments like "// Skip the header row when processing data" to explain the purpose and reasoning behind your code.

// Single-line comment
var x = 5; // Another comment

/* Multi-line comment
   This can span
   multiple lines */
var y = 6;

/*
var a = 1;
var b = 2;
*/
// The code above is commented out

// Prevent execution for testing
// console.log("This won't run");