Comments and Best Practices0%

Comments and Best Practices

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Comments and Best Practices in JavaScript

Writing code that works is only the first step; writing code that is readable, maintainable, and understandable by your teammates (and future you) separates junior coders from seasoned software engineers.


1. Comment Types in JavaScript

JavaScript provides two primary syntax options for adding comments that are ignored by the JS engine:

A. Single-Line Comments (//)

Use for brief explanations of a single line:

JavaScript
// Calculate total cart price with GST tax rate of 18%
const taxRate = 0.18;
const totalWithTax = subtotal * (1 + taxRate); // Inline comment

B. Multi-Line Block Comments (/* ... */)

Use for longer architectural notes or temporary code disabling:

JavaScript
/*
The following authentication algorithm validates:
1. Token signature using HMAC-SHA256
2. Expiration timestamp (exp claim)
3. User active status in PostgreSQL database
*/
function verifySessionToken(token) {
// ...
}

2. Professional Documentation: JSDoc Comments (/** ... */)

Top engineering teams use JSDoc comments. JSDoc allows code editors (like VS Code) to display rich tooltips, type hints, and autocompletion:

JavaScript
/**
* Calculates the final discounted price for an enrolled student.
*
* @param {number} originalPrice - The standard catalog price in INR.
* @param {number} discountPercent - Discount percentage (e.g., 20 for 20%).
* @returns {number} The final rounded price after discount.
*/
function calculateCourseDiscount(originalPrice, discountPercent) {
const discountAmount = originalPrice * (discountPercent / 100);
return Math.round(originalPrice - discountAmount);
}

When you hover your mouse over calculateCourseDiscount anywhere in your codebase, VS Code will display the parameters and return types automatically!


3. When NOT to Write Comments (Code Smells)

Pro Tip
[!TIP] Golden Rule of Clean Code: Good code is self-documenting. Comments should explain WHY something is done, not WHAT is done.

❌ Bad: Redundant Comments

JavaScript
// Set age to 25
let age = 25;
 
// If user is greater than 18
if (age > 18) {
// Allow entry
allowEntry();
}

❌ Bad: Using Comments to Explain Cryptic Variable Names

JavaScript
let d = 86400; // number of seconds in a day

✅ Clean & Self-Documenting:

JavaScript
const SECONDS_IN_A_DAY = 86400;

4. Essential JavaScript Naming Conventions

Follow standard JavaScript community conventions:

Identifier TypeConventionExample
Variables & PropertiescamelCaseuserName, totalAmount, isModalOpen
Functions & MethodscamelCase (Verb-based)getUserProfile(), calculateTotal(), fetchCourses()
BooleansPrefix with is, has, canisLoading, hasPermission, canSubmit
Classes & ComponentsPascalCaseUserCard, PaymentGateway, ShoppingCart
Global ConstantsUPPER_SNAKE_CASEMAX_RETRIES, DEFAULT_TIMEOUT_MS

5. Enable Strict Mode: "use strict"

Strict Mode eliminates silent errors in JavaScript by converting them to throw runtime exceptions:

JavaScript
"use strict";
 
// Without strict mode, mistyping a variable creates an accidental global!
// With strict mode, this throws ReferenceError: userName is not defined
userName = "Sumit";
Note
[!NOTE] All modern ES6 modules (import/export) and React/Next.js components run in strict mode automatically.

Interactive Quiz

Practice Quiz

Question 1
What is the syntax for a single-line comment in JavaScript?
Question 2
What is the primary purpose of writing JSDoc comments (/** ... */)?
Question 3
According to clean code principles, what should comments primarily explain?
Question 4
What casing convention is standard in JavaScript for functions and variable names?
Question 5
What does adding "use strict"; at the top of a JavaScript file enforce?
Next Lesson

Arithmetic Operators

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Data TypesArithmetic Operators

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext