Comments and Readability
学习如何 编写 code 那个 humans 能读取: comments, naming, 格式化, and 当不 到 comment.
你将学到
- three 类型的 comments and 当到 use 每个
- 为什么好 naming reduces 需要 for comments
- 如何 编写 comments 那个解释 '为什么', 不 '什么'
- 格式化约定那个 improve readability
- 关系之间 readability and maintainability
概念讲解
Comments and Readability
Readability 是 the measure of how easily a human can understand your code. Programs are read far more often than they are written — sometimes by others, sometimes by you months later. Code that is easy to read is easier to debug, easier to extend, and less likely to harbor bugs. Writing readable code is a professional skill, not an optional nicety.
Types of Comments
Most languages support single-line comments (// in JavaScript) and multi-line comments (/* ... */). JavaScript also has JSDoc comments (/** ... */) that document function signatures for tools and editors:
// Single-line: a brief note
/* Multi-line: use for longer
explanations that span lines */
/** JSDoc: documents a function for tooling
* @param {number} price - the item price
* @returns {number} the price with tax
*/
Comment the Why, Not the What
The most common commenting mistake is describing what the code does — which the code already shows. Good comments explain *why* the code does something: the business reason, the workaround, the constraint:
// BAD: describes what the code already says
const total = price * quantity; // multiply price by quantity
// GOOD: explains the why
const total = price * quantity; // bulk discount applied at checkout
Naming as Documentation
The best comment is a well-chosen name. When you name a variable daysSinceLastLogin instead of d, the code documents itself. When you name a function isEligibleForDiscount instead of 检查, the intent is clear without a single comment. Good naming eliminates most comments. Reserve comments for the cases where the code genuinely cannot speak for itself — non-obvious algorithms, external constraints, or bug-fix workarounds.
Formatting Conventions
Consistent formatting makes code scannable. Follow these principles:
- Indent consistently — 2 or 4 spaces, pick one and stick with it.
- Keep lines short — under 80–100 characters so code fits on screen.
- Group related statements — blank lines between logical sections.
- Align operators in long expressions for visual scanning.
Most teams use a formatter (like Prettier) to enforce these automatically, so you can focus on the logic instead of the layout.
Readability vs. Cleverness
Resist the urge to write "clever" one-liners that are hard to understand. A five-line solution that is obvious is better than a one-line solution that requires five minutes to decode. Code is a communication tool, not a puzzle. The smartest code is the code that the next reader understands fastest.
示例代码
// BAD: unclear naming, redundant comments, poor formatting
function p(d){let t=0;for(let i=0;i<d.length;i++){t+=d[i].p*d[i].q}return t} // calc total
// GOOD: clear naming, comments only where needed, readable format
function calculateOrderTotal(items) {
let total = 0;
for (const item of items) {
total += item.price * item.quantity;
}
return total;
}
// Comment explaining a non-obvious business rule:
function applyShipping(total) {
// Free shipping threshold was raised from $50 to $75 in Q3 2024
if (total >= 75) return 0;
return 5.99;
}
// JSDoc for public API functions:
/** Calculate the total cost of an order including shipping.
* @param {Array} items - array of {price, quantity} objects
* @returns {number} total cost in dollars
*/
function checkout(items) {
const subtotal = calculateOrderTotal(items);
const shipping = applyShipping(subtotal);
return subtotal + shipping;
}
坏 version 是单个行 那个是 nearly 不可能到 读取. 好 version uses descriptive names, 仅 comments 非-明显 business 规则, and 包含 JSDoc for 公共函数.
动手试一试
- Markdown Previewer
好 documentation uses Markdown for 格式化. Preview 你的 README and comment-样式 docs 这里.
- Code Diff
Compare two versions 的 code — practical 方式到 see 如何 readability improvements 更改 file.
常见错误
错误写法
编写 comments 那个只是 restate code.
正确做法
如果 comment says 相同 thing as code, 删除它. Use comments 到解释 intent, constraints, or 非-明显 reasons — 不到 narrate 语法.
错误写法
Using abbreviations or 单个-letter 变量 names 到保存输入.
正确做法
你读取 code ten 次数更多 than 你编写它. 类型完整 name: customerEmailAddress, 不 cea. 你的 IDE's autocomplete 制作长 names cost 无.
错误写法
Leaving commented-out code 块 in codebase.
正确做法
删除 dead code. Version control (Git) preserves history — 你能 总是 retrieve 旧 code. Commented-out 块 clutter file and confuse readers.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for comment 语法, JSDoc 标签, and 格式化约定.
练习 Comments and Readability
3 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。