Best Practices for Writing Clean and Scalable JavaScript Code
Piyush Chandak
Posted on November 7, 2024
Clean code is not just about functionality — it’s about readability, maintainability, and setting the stage for future growth.
It is essential for writing clean, reliable, and scalable code. Without them, code can quickly become messy, hard to read, and difficult to maintain, leading to more bugs, slower development, and frustration for the team. Good coding practices help keep projects organized, making it easier to understand, debug, and extend, especially as applications grow.
Ultimately, they set a strong foundation that ensures the software is robust, adaptable, and easier for everyone to work with.
I have categorise it in 3 parts
- Common Rules
- Frontend Specific Rules
- Backend Specific Rules
Common Rules
- Think Before Coding: Plan logic and approach before jumping into code.
- Naming Conventions:
- Use camelCase for variables, functions, and objects.
- Use PascalCase for classes and constructors.
- User Upper case with separated by underscores for constants
- Avoid abbreviations; make names descriptive.
Example:
fetchUserData()
instead ofgetData()
let userInfo = { ... }; // camelCase
class UserMeta { ... }; // Pascal Case
const APP_NAME = "Rule Book"; // Upper case with separated by underscore
- Keep Functions Small and Focused: Aim for functions with 50 lines or fewer. Each function should have a single responsibility.
- Reuse and Extend: Write reusable functions and make them flexible for future extensions.
- Avoid Deep Nesting: Limit nesting to 2 levels for readability. Separate Business Logic from Function Calls: Keep function logic and business rules in separate modules.
- Write Modular Code: Group similar functions in modules to keep code organized and reusable.
- Prefer Async/Await Over Promises: Async/await improves readability and handles async code in a synchronized way. Use try/catch for error handling.
- Document Complex Code: Add comments where logic is complex to help others understand and avoid future bugs.
- Follow the DRY Principle: Avoid duplicating code. Reuse functions and extract common logic to helpers.
- Follow ES6 Standards:
- Use let and const instead of var for variable declarations.
- Use destructuring for arrays and objects, e.g.,
- Prefer the spread operator (…) for copying and merging objects and arrays.
const { name, age } = user; // Destructuring Object
const [name, age]= ["John", 28];// Destructuring Array
const userInfo = { ...user, name: 'Ally' }; // Spread Operator
- Use a Linter and Formatter: Tools like ESLint and Prettier help enforce consistent spacing, indentation, and style across the codebase.
- Organize Constants: Store all constant values and error messages in a separate file for easy access and maintainability. Utilize Ternary Operators for Short Conditions: Replace simple if/else statements with ternaries where appropriate.
- Security and Updates:
- Run
npm audit
and keep dependencies updated to avoid security vulnerabilities. - Remove unused packages to reduce bloat and potential security risks.
Frontend Specific Rules
- Avoid Redundant: DOM Manipulations: Minimize direct DOM manipulations; leverage frameworks to update the UI efficiently.
- Error Handling on API's: Handle errors gracefully in UI to prevent application crashes and provide feedback to the user.
- Avoid Excessive Inline Styles: Use SCSS or CSS files or styling frameworks like Bootstrap, Tailwind to keep code clean and maintainable.
- Minimise Package Usage: Avoid unnecessary libraries. Use native solutions or carefully chosen libraries to keep the project lightweight.
-
Follow a Consistent Pattern: Establish and adhere to a consistent naming structure throughout your application.
Example: Use
/dashboard/settings
instead of/settingsDashboard
-
Avoid Special Characters: Stick to lowercase letters, hyphens (-), and avoid spaces, underscores, or special characters.
Example:
/user-profile
is better than/user_profile
or/UserProfile
. -
Reflect Navigation Hierarchies: Use URLs that reflect the structure of the content or navigation.
Example:
/products/electronics/phones
to show a clear path. -
Keep URLs Simple and Short: Avoid overly long or complex URLs that could confuse users.
Example:
/blog/2024/best-practices
instead of/blog/posts/2024/the-best-practices-we-should-follow
.
Backend Specific Rules
- Code Principles:
- Follow SOLID principles (especially SRP and Dependency Injection) to ensure code is modular, readable, and testable.
- Use design patterns like Factory or Singleton where they fit naturally.
- Error Handling and Logging:
- Log errors with sufficient details for debugging.
- Trigger alerts (e.g., email/Slack) for critical errors so they can be addressed immediately.
- Use consistent error formats for APIs to make debugging easier on the frontend.
- Folder Structure and File Organization:
- Routes: Define routes and add validations/guards.
- Controllers: Handle request parsing, service calls, and response formatting; avoid business logic here.
- Services: Implement business logic, following single-responsibility principles.
- DTOs: Define data transfer objects for request/response structures. Models: Define database models and schemas.
- Documentation:
- Use Swagger or similar tools to document APIs for easy understanding and testing.
- Document important services and complex business logic to help other developers.
- Unit Testing: Write test cases to catch bugs early and ensure code reliability.
- Error Logging for APIs: Log API calls and errors systematically, enabling easier debugging and monitoring.
- Use Environment Variables: Store configuration values and secrets in environment variables to avoid hardcoding them.
- Code Reviews and Quality Checks: Regularly review code with tools like SonarQube or other code analyzer to catch issues early and maintain high standards.
- API Naming:
-
Use Nouns for Resource Names: API endpoints should represent resources using nouns, not verbs.
Example: Use
/users
instead of/getUsers
. -
Consistent Naming Conventions: Stick to a standard format, such as using lowercase and separating words with hyphens (kebab-case).
Example:
/user-profiles
instead of/UserProfiles
. -
Plural Naming for Collections: When referring to a collection of resources, use plural names.
Example:
/products
for a list of all products, and/products/{id}
for a specific product. - Keep Endpoints Short and Descriptive: Keep URLs short but meaningful. Avoid using redundant words or unnecessary information.
Example:
/orders/{id}/status
instead of/orders/order-status/{id}
. - HTTP Methods: Match the HTTP method to the action you are performing:
- GET for retrieving data
- POST for creating data
- PUT/PATCH for updating data
- DELETE for removing data
-
Version API: Include a version number in the URL to manage updates and changes.
Example:
/v1/users
.
Writing clean and maintainable code is a journey filled with evolving best practices, and while it's impossible to cover everything in a single blog post, these guidelines provide a strong foundation. Remember, code isn't just written for machines; it's written for developers to read and improve upon. Embracing these practices will not only make your projects better but also elevate your skills and collaboration with your team.
Good code is its own best documentation
- Steve McConnell
Posted on November 7, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.