JavaScript · Chapter 55 of 55

JavaScript Best Practices

Writing good JavaScript is about more than making it work — it's about making code readable, maintainable, and free of common pitfalls that trip up teams over time.

Following consistent conventions like using `const`/`let` over `var`, strict equality, and descriptive names will make your code easier for others (and future you) to understand and extend.

Style and structure

Use `const` by default, `let` when needed, and avoid `var`. Use strict equality (`===`), meaningful variable names, and keep functions small and focused on one task.

Avoiding common pitfalls

Always handle Promise rejections and errors, avoid polluting the global scope, comment on WHY not WHAT, and use tools like ESLint and Prettier for consistency.

Example 1 (javascript)
// Good: descriptive names, const by default
const MAX_RETRIES = 3;
function fetchWithRetry(url, attempt = 1) {
  console.log(`Attempt ${attempt} for ${url}`);
}
fetchWithRetry("https://api.example.com");
Output
Attempt 1 for https://api.example.com

Clear naming and default parameters make intent obvious.

Example 2 (javascript)
async function safeFetch(url) {
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error("HTTP " + res.status);
    return await res.json();
  } catch (err) {
    console.error("Fetch failed:", err.message);
    return null;
  }
}
Output
(handles errors gracefully)

Always check res.ok and wrap awaited code in try/catch.

Key points

  • Prefer const/let over var, and === over ==.
  • Keep functions small, focused, and descriptively named.
  • Always handle errors in async code with try/catch or .catch().
  • Use linters (ESLint) and formatters (Prettier) for consistency.
💡 Note: Readable, consistent code saves far more time in maintenance than any clever one-liner ever will.

📝 Quick Quiz

1. Which equality operator should you prefer?

2. What should you avoid using in modern JavaScript?

3. What tool helps enforce consistent code style?