Good practices for Javascript Applications (Clean Code)

Good practices for Javascript Applications (Clean Code)

10 rules to explain the basics

ยท

3 min read

I am writing this best practices guide for creating and maintaining JavaScript applications for my team. I am making it extremely simple and very easy to understand so that it is comprehensible and quickly applicable.

๐Ÿ’ก
Note: This guide will be primarily based on the clean code design pattern.

Readable

Code should be easy to read and understand.

// Bad
function calcsal(a, b, c) {
    return a * b + c;
}

// Good
function calculateSalary(hoursWorked, hourlyRate, bonus) {
    return hoursWorked * hourlyRate + bonus;
}

Descriptive Names

Use meaningful and descriptive names for variables, functions, and classes.

// Bad
let x = 10;

// Good
let maxUserLimit = 10;

Single Responsibility Principle

Each function or class should have only one reason to change.

// Bad
function manageUserAccount(username, password, isAdmin) {
    saveUser(username, password);
    if (isAdmin) {
        grantAdminPrivileges(username);
    }
}

// Good
function saveUser(username, password) {
    // Code to save user
}

function grantAdminPrivileges(username) {
    // Code to grant admin privileges
}

Avoid Magic Numbers

Use named constants instead of hardcoding numbers.

// Bad
if (score > 75) {
    console.log("Passed");
}

// Good
const PASSING_SCORE = 75;
if (score > PASSING_SCORE) {
    console.log("Passed");
}

Minimize Side Effects

Functions should avoid changing the state outside their scope.

// Bad
let total = 0;

function addToTotal(amount) {
    total += amount;
}

// Good
function add(a, b) {
    return a + b;
}

Use Comments Sparingly

Comments should explain why something is done, not what is done.

// Bad
let i = 0; // Initialize counter

// Good
// Retry up to 3 times if connection fails
for (let attempt = 0; attempt < 3; attempt++) {
    if (connect()) {
        break;
    }
}

DRY Principle (Don't Repeat Yourself)

Avoid duplicating code by abstracting common functionality.

// Bad
function calculateAreaOfRectangle(width, height) {
    return width * height;
}

function calculateAreaOfSquare(side) {
    return side * side;
}

// Good
function calculateArea(shape) {
    if (shape.type === 'rectangle') {
        return shape.width * shape.height;
    } else if (shape.type === 'square') {
        return shape.side * shape.side;
    }
}

Consistent Formatting

Use consistent indentation, spacing, and style throughout the code.

// Bad
function fetchData(){
 let response = fetch('http://example.com');
 return response.json();
}

// Good
function fetchData() {
    let response = fetch('http://example.com');
    return response.json();
}

Error Handling

Properly handle errors and exceptions. Usage of Sentry can be also very good.

// Bad
function readFile(filepath) {
    return fs.readFileSync(filepath, 'utf8');
}

// Good
function readFile(filepath) {
    try {
        return fs.readFileSync(filepath, 'utf8');
    } catch (err) {
        console.log("File not found");
        // Sentry is also amazing to catch errors
        // Option 1
        return {
            status: err.status, // check err status
            message: err.message // or custom message
        }
        // Option 2
        throw new Error(err)
    }
}

Use Libraries

Leverage existing libraries and frameworks to avoid reinventing the wheel.

// Bad
function parseJSON(jsonString) {
    return JSON.parse(jsonString);
}

// Good
function parseJSON(jsonString) {
    return JSON.parse(jsonString);
}

Following these principles ensures that your code is clean, maintainable, and efficient.

Guillaume Duhan

ย