Code Comments
Overview
Comments are lines of text in your code that the JavaScript engine completely ignores.
They are essential for leaving notes for your future self, explaining complex logic to other developers, or temporarily disabling code while debugging.
Syntax
Use // for quick notes and /* */ for detailed documentation or temporarily removing code chunks.
// This is a single-line comment.
let x = 5; // You can also put it at the end of a line.
/*
This is a multi-line comment.
It is useful for writing longer explanations
or temporarily commenting out large blocks of code.
*/
let y = 10;JSDoc is a standard for documenting code. Modern editors like VS Code read these comments and provide helpful tooltips when you use the function elsewhere.
/**
* Adds two numbers together.
* @param {number} a - The first number
* @param {number} b - The second number
* @returns {number} The sum of a and b
*/
function add(a, b) {
return a + b;
}Common Pitfalls
- Writing 'redundant' comments that just repeat what the code does (e.g., `// add 1 to i i++`). Comments should explain why the code is doing something, not what it is doing.
- Leaving commented-out 'zombie code' in your final production builds.
Interview Questions
Technically, yes, if the file size increases significantly, it takes longer to download. However, in modern development, we use 'minifiers' before deploying to production. Minifiers automatically strip out all comments and whitespace, so they have zero impact on production performance.
Real-World Example
When building a public library, developers use JSDoc comments so that when other developers install their package, they get automatic autocomplete and documentation directly in their editor.
/**
* Formats a date into a readable string
* @param {Date} dateObj
* @returns {string}
*/
function formatDate(dateObj) {
// complex logic here
}Check Your Knowledge
Test your understanding of Code Comments with these quick questions.