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 bulky if/else blocks.
  • Array Methods: Prefer .map(), .filter(), and .reduce() over traditional for loops.
  • Async/Await: Use async/await syntax instead of chaining .then() callbacks for cleaner asynchronous code.

Naming Conventions

  • Variables: Use camelCase.
  • Descriptive Names: Favor descriptive names over concise ones. getUserProfile is better than getData.
  • Consistent Verbs: Stick to a pattern like get, create, upload, delete. Don’t mix fetchUser and getUser.
  • Booleans: Prefix boolean variables with is, has, or should (e.g., isLoggedIn, hasPermission).
  • Classes: Use PascalCase and nouns for class names (e.g., userProfile, not updateUser).
  • Constants: Capitalize constant values (e.g., SECONDS_IN_A_DAY).
  • Avoid Single Letters: Never use one-letter variables like x or e (unless it’s a standard loop index i).

Debugging Tip

  • Smart Logging: Instead of console.log(foo), use console.log({ foo }). This prints the variable name and its value, making debugging much easier.