iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Best Practices

Most "best practices" boil down to making code obvious for the reader six months from now.

The shortlist

  • const by default. let only when reassignment is needed. Never var.
  • === 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/catch over every line.
  • Async everywhere — use async/await for clarity, Promise.all for parallelism.
  • Avoid implicit globals. Use modules or wrap in IIFEs.
  • Type-check with TypeScript or JSDoc on anything that crosses a module boundary.

Naming

KindConventionExample
Variables & functionscamelCaseuserName
Classes & constructorsPascalCaseUserAccount
Constants (true compile-time)UPPER_SNAKEMAX_RETRIES
Booleansis / has / should prefixisReady, hasError
Private fields#field#cache
Fileskebab-case or PascalCase for componentsuser-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 await when work is independent — use Promise.all.
  • Memoize expensive pure functions.
  • Pass primitives into hot loops; spread once at the boundary.
  • Defer non-critical scripts with defer or dynamic import().
  • 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') { /* … */ }

Test yourself

Q1. Modern default declaration is…
Q2. Default equality operator should be…
Q3. For 4+ optional parameters, the recommended pattern is…

Discussion

Loading…