JavaScript Best Practices in Bullet Points
There are countless articles about JavaScript best practices, but sometimes you just need a quick checklist. Here is a curated list of rules I follow to keep my code clean and maintainable.
You can also enforce many of these automatically by adding an .eslintrc file to your project root.
Code Structure
- Avoid Deep Nesting: Do not deep nest
map,filter, or loops. Decompose complex logic into separate, smaller functions. - Don’t Over-Comment: Good code documents itself. Only write comments when the “why” isn’t obvious from the code.
- Limit Arguments: Try not to take more than two arguments in a function. If you need more, pass a single configuration object (destructuring makes this easy).
- DRY (Don’t Repeat Yourself): If you see similar code appearing in multiple places, refactor it into a shared utility or function.
- Keep Functions Small: Large functions are hard to test and debug. Split them up.
- Single Responsibility: A function should do one thing and do it well. Avoid side effects (changing external state) whenever possible.
Syntax & Style
- Use Spread Syntax: Use the spread operator (
...) to copy arrays/objects or merge them. It’s cleaner than old-school methods. - Template Literals: Always prefer template literals (
${var}) over string concatenation (+). - Ternary Operators: For simple conditional assignments, use ternary operators (
condition ? true : false) instead of bulkyif/elseblocks. - Array Methods: Prefer
.map(),.filter(), and.reduce()over traditionalforloops. - Async/Await: Use
async/awaitsyntax instead of chaining.then()callbacks for cleaner asynchronous code.
Naming Conventions
- Variables: Use
camelCase. - Descriptive Names: Favor descriptive names over concise ones.
getUserProfileis better thangetData. - Consistent Verbs: Stick to a pattern like
get,create,upload,delete. Don’t mixfetchUserandgetUser. - Booleans: Prefix boolean variables with
is,has, orshould(e.g.,isLoggedIn,hasPermission). - Classes: Use
PascalCaseand nouns for class names (e.g.,userProfile, notupdateUser). - Constants: Capitalize constant values (e.g.,
SECONDS_IN_A_DAY). - Avoid Single Letters: Never use one-letter variables like
xore(unless it’s a standard loop indexi).
Debugging Tip
- Smart Logging: Instead of
console.log(foo), useconsole.log({ foo }). This prints the variable name and its value, making debugging much easier.