JS Best Practices
Most "best practices" boil down to making code obvious for the reader six months from now.
The shortlist
constby default.letonly when reassignment is needed. Nevervar.===and!==only. Loose equality leads to coercion surprises.- One thing per function. Long methods are a smell; extract.
- Prefer non-mutating operations —
map,filter,reduce, spread,toSorted. - Catch errors at the boundary (HTTP handler, event handler). Don't sprinkle
try/catchover every line. - Async everywhere — use
async/awaitfor clarity,Promise.allfor parallelism. - Avoid implicit globals. Use modules or wrap in IIFEs.
- Type-check with TypeScript or JSDoc on anything that crosses a module boundary.
Naming
| Kind | Convention | Example |
|---|---|---|
| Variables & functions | camelCase | userName |
| Classes & constructors | PascalCase | UserAccount |
| Constants (true compile-time) | UPPER_SNAKE | MAX_RETRIES |
| Booleans | is / has / should prefix | isReady, hasError |
| Private fields | #field | #cache |
| Files | kebab-case or PascalCase for components | user-service.js, UserCard.jsx |
Module discipline
JS
// ✓ Named exports are searchable and refactor-safe
export function loadUser(id) { /* … */ }
export const TIMEOUT = 5000;
// ❌ Default exports get renamed everywhere
export default loadUser;
Performance habits that pay off
- Don't loop with
awaitwhen work is independent — usePromise.all. - Memoize expensive pure functions.
- Pass primitives into hot loops; spread once at the boundary.
- Defer non-critical scripts with
deferor dynamicimport(). - Profile before optimising. Hot code is often somewhere unexpected.
Tip: Lint and format on save. ESLint catches mistakes; Prettier removes the bikeshedding. Both run automatically with a Git pre-commit hook.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Best Practices!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the recommended equality operator.
if (status
'open') { /* … */ }
Three characters — strict equality.
Discussion
Loading…