30 Best Practices for Clean JavaScript Code [Bonus tips at the end

No waste of time. Let's go directly into it.

1. Avoid Global Variables

Bad Example:

var x = 10;
function calculate() {
    // Using the global variable x
    return x * 2;
}j

Good Example:

function calculate(x) {
    // Pass x as a parameter
    return x * 2;
}
const x = 10;
const result = calculate(x);

Avoid polluting the global scope with variables to prevent conflicts and improve code maintainability.

2. Use Arrow Functions for Concise Code

Bad Example:

function double(arr) {
    return arr.map(function (item) {
        return item * 2;
    });
}

Good Example:

const double = (arr) => arr.map((item) => item * 2);

Arrow functions provide a concise and more readable way to define small functions.

3. Error Handling with Try-Catch Blocks

Bad Example:

function divide(a, b) {
    if (b === 0) {
        return "Division by zero error!";
    }
    return a / b;
}

Good Example:

function divide(a, b) {
    try {
        if (b === 0) {
            throw new Error("Division by zero error!");
        }
        return a / b;
    } catch (error) {
        console.error(error.message);
    }
}

Use try-catch blocks to handle errors gracefully and provide meaningful error messages.

Read More