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.
// 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");Attempt 1 for https://api.example.comClear naming and default parameters make intent obvious.
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;
}
}(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.
