Comments are non-executable explanatory notes written directly within source code. The JavaScript engine completely ignores comments during compilation and execution. When utilized effectively, comments transform complex codebases into readable, maintainable, and self-explanatory software systems.
JavaScript provides two native syntax forms for commenting code:
Used for brief inline explanations or quick single-line notes. Everything from the double slash to the end of that specific physical line is ignored:
// Calculate student final grade based on theory and lab practicals
const totalScore = theoryMarks + practicalMarks; // Inline note
Used for extensive conceptual descriptions, licensing headers, or temporarily commenting out large blocks of code during debugging:
/*
* Algorithm: Binary Search Implementation
* Time Complexity: O(log N)
* Prerequisites: Array must be sorted in ascending order
*/
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
// ... search logic
}
JSDoc is the industry standard for documenting JavaScript functions, classes, and APIs. Modern editors like VS Code parse JSDoc annotations to provide rich autocomplete tooltips and static type safety warnings:
/**
* Calculates the compounded interest on a financial investment.
*
* @param {number} principal - The initial capital invested in INR.
* @param {number} rate - Annual interest rate (percentage, e.g. 7.5).
* @param {number} years - Duration of investment in whole years.
* @returns {number} The total compounded amount formatted to 2 decimals.
* @throws {Error} Throws error if principal or years are negative.
*/
function calculateCompoundInterest(principal, rate, years) {
if (principal < 0 || years < 0) {
throw new Error("Financial values cannot be negative.");
}
const amount = principal * Math.pow((1 + (rate / 100)), years);
return Number(amount.toFixed(2));
}
| Antipattern (Avoid) | Clean Code Best Practice (Adopt) |
|---|---|
Stating the Obvious:let i = 0; // set i to 0 |
Write self-explanatory code that needs no comment:let retryAttemptCount = 0; |
| Leaving "Zombie" Dead Code: Commenting out 50 lines of dead legacy code "just in case". |
Delete dead code cleanly. Git version control preserves complete historical records forever. |
| Misleading / Outdated Comments: Code was updated but the comment was never revised. |
Maintain documentation integrity: update comments whenever associated logic changes. |
Exam Question: "What are the benefits of source code documentation and minification in production deployment?"
Answer: In development, extensive JSDoc comments improve code readability, reduce onboarding time for team members, and prevent logic bugs. Before production deployment, build tools (minifiers) strip out all whitespace and comments, reducing file payload by up to 60% for faster web page load speeds.
How does JavaScript represent and manipulate textual data? Proceed to: JavaScript Strings & Template Literals →