DEV Community

Cover image for Writing Clean Code in JavaScript – Best Practices for Readable and Maintainable Code
Patoliya Infotech
Patoliya Infotech

Posted on

Writing Clean Code in JavaScript – Best Practices for Readable and Maintainable Code

Building scalable and effective apps requires writing JavaScript code that is clear, legible, and maintainable. Writing code that is simple for others to understand and change, including your future self, is essential whether you're working alone or with a team.

Clean code guarantees long-term maintainability, facilitates cooperation, and improves debugging.

To assist you in writing clean JavaScript code, we will go further into best practices, sophisticated methods, and useful tactics in this blog.

1. Use Meaningful and Descriptive Variable Names

It is important for variable names to be descriptive and unambiguous. Avoid using unclear terminology, single-character names (except for loop iterators), and abbreviations. The code is self-explanatory because of descriptive names, which eliminates the need for extra comments.

Bad Example:

let x = 10;
let y = 20;
let z = x + y;
Enter fullscreen mode Exit fullscreen mode

Good Example:

let firstNumber = 10;
let secondNumber = 20;
let sum = firstNumber + secondNumber;
Enter fullscreen mode Exit fullscreen mode

Tips for Naming Variables:

  • Use camelCase for variables and functions: userAge, calculateTotal.
  • Use PascalCase for classes and constructors: UserProfile, ShoppingCart.
  • Use UPPER_SNAKE_CASE for constants: MAX_ALLOWED_USERS, API_URL.
  • Boolean variables should start with is, has, or should: isAdmin, hasAccess.

2. Keep Functions Small and Focused

A function should adhere to the Single Responsibility Principle (SRP) and carry out a single, defined task. Divide a function into smaller, reusable ones if it gets too complicated.

Bad Example:

function processUserData(user) {
    console.log(`User: ${user.name}`);
    user.isActive = true;
    sendWelcomeEmail(user.email);
    updateDatabase(user);
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

function activateUser(user) {
    user.isActive = true;
}

function notifyUser(email) {
    sendWelcomeEmail(email);
}

function processUserData(user) {
    console.log(`User: ${user.name}`);
    activateUser(user);
    notifyUser(user.email);
    updateDatabase(user);
}
Enter fullscreen mode Exit fullscreen mode

Key Principles for Functions:

  • Functions should do one thing and one thing only.
  • Functions should be short – ideally, no more than 10-15 lines.
  • Use function parameters instead of global variables.
  • Use meaningful names for functions that describe what they do.

3. Use Consistent Formatting and Code Style

Readability is increased with consistent formatting. Make sure that bracket placement, spacing, and indentation are all consistent.

Bad Example:

function greet(name){console.log("Hello, "+name);}

Enter fullscreen mode Exit fullscreen mode

Good Example:

function greet(name) {
    console.log(`Hello, ${name}`);
}

Enter fullscreen mode Exit fullscreen mode

Tools for Code Formatting:

  • ESLint: Enforces coding standards and identifies errors.
  • Prettier: Auto-formats code for consistency.
  • EditorConfig: Maintains consistent styles across different editors.

4. Avoid Using Magic Numbers and Strings

Code is more difficult to comprehend and maintain when it contains hardcoded strings and magic numbers. Named constants should be used instead.

Bad Example:

if (user.role === "admin") {
    grantAccess();
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

const ADMIN_ROLE = "admin";
if (user.role === ADMIN_ROLE) {
    grantAccess();
}
Enter fullscreen mode Exit fullscreen mode

5. Use Default Parameters and Destructuring

Code readability is enhanced and duplication is decreased using modern JavaScript capabilities.

Bad Example:

function createUser(name, age, country) {
    const user = {
        name: name || "Unknown",
        age: age || 0,
        country: country || "Unknown",
    };
    return user;
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

function createUser({ name = "Unknown", age = 0, country = "Unknown" } = {}) {
    return { name, age, country };
}
Enter fullscreen mode Exit fullscreen mode

6. Handle Errors Properly

Effective error management improves user experience and avoids unplanned crashes.

Bad Example:

function getUserData(userId) {
    return fetch(`https://api.example.com/users/${userId}`)
        .then(response => response.json())
        .catch(error => console.log(error));
}
Enter fullscreen mode Exit fullscreen mode

Good Example:

async function getUserData(userId) {
    try {
        const response = await fetch(`https://api.example.com/users/${userId}`);
        if (!response.ok) throw new Error("User not found");
        return await response.json();
    } catch (error) {
        console.error("Error fetching user data:", error);
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Use Comments Wisely

Comments should explain why something is done, not what the code does.

Bad Example:

// Increment count by 1
count = count + 1;
Enter fullscreen mode Exit fullscreen mode

Good Example:

// Increase count when a new user joins
count++;
Enter fullscreen mode Exit fullscreen mode

8. Follow the DRY (Don’t Repeat Yourself) Principle

Avoid duplicating code. Instead, use functions, loops, or reusable components.

Bad Example:

function greetUser(user) {
    console.log("Hello, " + user.name);
}
function greetAdmin(admin) {
    console.log("Hello, " + admin.name);
}

Enter fullscreen mode Exit fullscreen mode

Good Example:

function greet(person) {
    console.log(`Hello, ${person.name}`);
}
Enter fullscreen mode Exit fullscreen mode

9. Use Modern JavaScript Features

Leverage ES6+ features like let and const, template literals, arrow functions, and async/await.

Example:

const greet = (name) => console.log(`Hello, ${name}!`);
Enter fullscreen mode Exit fullscreen mode

10. Write Unit Tests

Testing your code ensures reliability. Use frameworks like Jest or Mocha.

Example:

const add = (a, b) => a + b;

test("adds two numbers", () => {
    expect(add(2, 3)).toBe(5);
});
Enter fullscreen mode Exit fullscreen mode

Seamless Java API integration starts with best practices and security! 🚀 Implement these strategies today to build robust, efficient, and secure applications.

Conclusion

Writing clean JavaScript code involves more than just following a set of guidelines; it additionally involves developing an attitude of efficiency, maintainability, and clarity.

Using the recommended practices described in this article will allow you to:

  • Make your code more readable so that others (and your future self) may comprehend it more easily.
  • Reduce the amount of time spent repairing errors by improving debugging and troubleshooting.
  • Create programs that are efficient and scalable so they may expand without becoming unmanageable.
  • Encourage improved teamwork to ensure efficient knowledge transfer and code reviews.

Keep in mind that developing code that is easy for people to read, edit, and maintain is what clean code is all about, not writing code that only machines can comprehend.

The quality of your JavaScript code will be improved by following these guidelines, regardless of your level of experience or desire to improve.

Develop these routines, incorporate them into your everyday tasks, and keep improving your coding approach. Clean coding is easier to understand the more you practice.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay