JavaScript 最佳实践
Clean code 约定, immutability, modern ES features, and avoiding 常见 footguns.
你将学到
- Preferring const and let over var, and === over ==
- Immutability 使用 spread and 非-mutating 数组方法
- Meaningful naming and 小, 单个-purpose 函数
- Consistent 错误 handling and avoiding silent failures
- Leveraging modern ES features 相反的 legacy 模式
概念讲解
Prefer Modern Declarations and Equality
Use const by default and let only when reassignment is necessary — never var. Always compare with === and !== to avoid type-coercion surprises (0 == "" is true, 0 === "" is false). Use ?? (nullish coalescing) for defaults instead of || when 0 or "" are valid values. These three habits alone prevent a large class of bugs.
Embrace Immutability
Prefer non-mutating operations: [...arr] to copy, arr.toSorted() (ES2023) instead of arr.排序(), and spread to update objects ({ ...obj, 键: newValue }). Immutability makes state changes predictable, enables cheap equality checks, and is the foundation of React and Redux patterns. When you must mutate, do it in a clearly marked, localized place.
Name Things Well
Names are the primary documentation of your code. Use descriptive, pronounceable names: userEmails not arr, isAuthenticated not flag. Booleans should start with 是, 有, or 能. Functions should be verbs (fetchUsers, calculateTotal). Keep functions small and focused on one task — if a function needs a comment to explain what it does, consider splitting it.
Handle Errors Explicitly
Never swallow errors with an empty catch. Log, rethrow, or recover meaningfully. Throw 错误 objects (not strings) so stack traces are preserved. Validate inputs at the boundaries of your system and fail fast with clear messages. Use custom error subclasses to distinguish failure types. An unhandled rejection should be a bug you fix, not a pattern you accept.
Use Modern ES Features
Replace legacy patterns with modern equivalents: template literals over concatenation, arrow functions over .bind(这个), destructuring over repeated property access, Promise.所有 over nested callbacks, optional chaining (?.) over manual null checks, and 对象.条目 / 对象.fromEntries for transformations. Modern syntax is not just shorter — it is less error-prone and more expressive.
Lint and Format
Use ESLint and Prettier to enforce conventions automatically. A consistent style across a team reduces cognitive load and prevents bike-shedding in code review. Enable strict mode ('use strict' or ES modules, which are strict by default). Run a linter in your editor and CI so issues are caught before they reach the main branch.
示例代码
// BAD: var, ==, mutation, magic names
var x = getData();
if (x == null) x = [];
x.push(transform(item));
// GOOD: const, ===, immutability, clear names
const existingItems = getData() ?? [];
const updatedItems = [...existingItems, transform(item)];
// BAD: nested null checks
const city =
user && user.address && user.address.city
? user.address.city
: "Unknown";
// GOOD: optional chaining
const cityName = user?.address?.city ?? "Unknown";
// BAD: mutating sort
const sorted = [...data];
sorted.sort((a, b) => a - b);
// GOOD: non-mutating sort (ES2023)
const sortedClean = data.toSorted((a, b) => a - b);
// BAD: silent error swallow
function parse(json) {
try {
return JSON.parse(json);
} catch (e) {
return null; // hides real bugs
}
}
// GOOD: explicit error handling with context
function parseSafe(json, context = "input") {
try {
return JSON.parse(json);
} catch (e) {
throw new Error(`Invalid JSON in ${context}: ${e.message}`);
}
}
// GOOD: small, named, single-purpose functions
const isActive = (user) => user?.status === "active";
const fullName = (user) => `${user.firstName} ${user.lastName}`.trim();
const toOption = (user) => ({ value: user.id, label: fullName(user) });
const activeOptions = users.filter(isActive).map(toOption);
Contrasts 坏 and 好模式: var 对比 const/let, == 对比 ===, mutation 对比 spread, manual 空检查对比可选 chaining, in-位置排序对比 toSorted, silent catch 对比 explicit 错误, and 小 named 函数 composed 到流水线.
动手试一试
- JSON Formatter
格式 and 验证 JSON — 边界哪里输入 validation matters 大多数.
- JSON Validator
验证数据结构之前处理 — 失败快 使用清晰错误.
常见错误
错误写法
Using var and == in modern code
正确做法
Use const 通过默认, let 当你 需要 reassignment, and 从不 var. 总是 use === and !== for comparison. 这些 two 更改 eliminate huge 类的 作用域 and coercion bugs.
错误写法
编写大 函数那个做 许多 things
正确做法
Keep 函数小 and focused on one responsibility. 如果函数 exceeds ~40 行 or 需要 comments 到解释它的 steps, extract helper 函数使用 descriptive names. 小函数是 easier 到测试, name, and reuse.
相关资源
相关速查表
- JavaScript Cheatsheet
Modern 语法, immutability 模式, and clean-code 约定.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。