Industry Best Practices
The conventions professional teams actually enforce â in style guides, code review, and CI. Adopt these now and your code will read like it was written by someone with years of experience.
Code Style & Language Use
constby default,letwhen needed,varnever.- Strict equality always (
===/!==). The only tolerated==isx == nullto match both null and undefined. - Small, single-purpose functions. If you need "and" to describe what a function does, split it.
- Early returns over nested ifs. Handle the error/edge case first and return; keep the happy path unindented.
- Descriptive names beat comments.
isEligibleForDiscountneeds no comment;chk(u)needs a paragraph. - Options objects for 3+ parameters â
createUser({ name, role, notify })instead of positional soup. - Prefer immutability: spread-into-new over mutate-in-place,
map/filterover index-fiddling loops.
// â Nested happy-path-last
function process(order) {
if (order) {
if (order.items.length > 0) {
// ... 20 lines ...
} else { throw new Error("empty"); }
} else { throw new Error("missing"); }
}
// â
Guard clauses, flat happy path
function process(order) {
if (!order) throw new Error("missing order");
if (order.items.length === 0) throw new Error("empty order");
// ... 20 lines, unindented ...
}
Async Code
- async/await over raw
.thenchains for application code; chains remain fine for one-liners. - Parallelize independent awaits with
Promise.allâ reviewers WILL flag sequential independent fetches. - Every promise needs an owner. No floating promises: await it, return it, or explicitly
void promise.catch(log). - Timeout and retry at boundaries. Any network call in production code gets a timeout; idempotent ones get retries with backoff.
- Use
AbortControllerto cancel requests that no longer matter (user navigated away, newer search superseded). return awaitinside try blocks so rejections are catchable locally.- Never block the event loop â no
readFileSync/heavy sync loops in servers. One slow handler stalls every connection.
Error Handling
- Throw
Errorobjects, never strings â you need the stack trace. - Create domain error classes (
class NotFoundError extends Error) so callers can branch on type, not message text. - Catch where you can act. Add context and rethrow (
throw new Error("loading profile failed", { cause: err })), recover with a fallback, or let it propagate to the central handler. - Empty catch blocks are bugs. At absolute minimum, log.
- Centralize: Express error middleware, process-level
unhandledRejectionlogging, and consistent error response shapes for APIs.
Modules & Project Structure
- One responsibility per file.
routes/users.js,services/email.js,utils/dates.jsâ not a 2000-lineapp.js. - Prefer named exports â they survive renames, autocomplete better, and grep cleanly. Default exports for a file's single main thing (a component, a class).
- No circular imports. If A needs B and B needs A, extract the shared piece into C.
- Keep side effects out of module top-level â importing a file should not connect to a database.
Tooling Every Team Uses
| Tool | What it enforces | Setup |
|---|---|---|
| ESLint | Bug-prone patterns: eqeqeq, no-floating-promises, unused vars | npm init @eslint/config |
| Prettier | Formatting â ends all style debates | npm i -D prettier + format-on-save |
| EditorConfig | Indent/encoding consistency across editors | .editorconfig file |
| Vitest / Jest | Behavior doesn't regress | npm i -D vitest |
| Husky + lint-staged | Lint/format run before every commit | Git hooks |
| TypeScript / JSDoc | Types â the eventual industry default | after this guide đ |
âšī¸ Style guides worth reading
The Airbnb JavaScript Style Guide is the most famous â skim it to see WHAT teams standardize and why. Google's and StandardJS are alternatives. Don't memorize; let ESLint enforce.
Git & Collaboration Habits
- Small, focused commits with imperative messages: "add retry to payment client", not "fixes stuff".
- Never commit secrets â
.envfiles stay in.gitignore; use environment variables. - README every project: what it does, how to run it, example usage. Your GitHub is your portfolio.
- Review your own diff before pushing. Half of all embarrassing bugs are visible in
git diff.
Security Basics (backend-flavored)
- Validate all external input at the boundary (request bodies, query params, file contents) â libraries like
zodmake this pleasant. - Never build queries/HTML by string concatenation â parameterized queries; escape or safely set text content.
- Keep dependencies patched:
npm audit, Dependabot. Fewer dependencies = smaller attack surface. - Don't leak internals in errors â stack traces to logs, sanitized messages to clients.