JavaScript Best Practices

Writing clean, maintainable, and efficient JavaScript code

✨ What are JavaScript Best Practices?

Best practices are proven methods and techniques that help you write better JavaScript code. Following these practices makes your code more readable, maintainable, and less prone to bugs.


// Good practice: Use meaningful variable names
const userAge = 25;
const userName = "John";

// Bad practice: Use unclear names
const a = 25;
const n = "John";
                                    

Core Best Practices

📝

Naming Conventions

Use clear, descriptive names

camelCase Descriptive Consistent
🔧

Code Structure

Organize code logically

Functions Modules Comments
🛡️

Error Handling

Handle errors gracefully

try-catch Validation Fallbacks

Performance

Write efficient code

Optimization Caching Minimal DOM

🔹 Variable and Function Naming

Use descriptive names that explain what the variable or function does:

Naming Rules:

  • Use camelCase for variables and functions
  • Use PascalCase for constructors and classes
  • Use UPPER_CASE for constants
  • Avoid abbreviations and single letters
// ✅ Good naming
const MAX_RETRY_ATTEMPTS = 3;
const userAccountBalance = 1500;

function calculateTotalPrice(items) {
    return items.reduce((total, item) => total + item.price, 0);
}

class UserAccount {
    constructor(name, email) {
        this.name = name;
        this.email = email;
    }
}

// ❌ Bad naming
const MRA = 3;
const uab = 1500;

function calc(i) {
    return i.reduce((t, x) => t + x.p, 0);
}

Output:

Good naming makes code self-documenting and easier to understand!

🔹 Use const and let Instead of var

Modern JavaScript prefers const and let for better scope control:

// ✅ Good: Use const for values that don't change
const API_URL = "https://api.example.com";
const users = ["Alice", "Bob", "Charlie"];

// ✅ Good: Use let for values that will change
let currentUser = null;
let isLoggedIn = false;

function login(username) {
    currentUser = username;
    isLoggedIn = true;
}

// ❌ Avoid: var has function scope issues
var message = "Hello"; // Can cause unexpected behavior

🔹 Always Use Semicolons

End statements with semicolons to avoid automatic insertion issues:

// ✅ Good: Explicit semicolons
const name = "John";
const age = 30;

function greet() {
    return "Hello!";
}

// ❌ Risky: Missing semicolons can cause problems
const name = "John"
const age = 30

function greet() {
    return "Hello!"
}

🔹 Error Handling Best Practices

Always handle potential errors in your code:

// ✅ Good: Proper error handling
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const userData = await response.json();
        return userData;
    } catch (error) {
        console.error("Failed to fetch user data:", error);
        return null; // Return fallback value
    }
}

// ✅ Good: Input validation
function calculateArea(width, height) {
    if (typeof width !== 'number' || typeof height !== 'number') {
        throw new Error('Width and height must be numbers');
    }
    
    if (width <= 0 || height <= 0) {
        throw new Error('Width and height must be positive');
    }
    
    return width * height;
}

Output:

Error handling prevents crashes and provides better user experience!

🔹 Function Best Practices

Write clean, focused functions that do one thing well:

Function Guidelines:

  • Single Responsibility: Each function should do one thing
  • Small Size: Keep functions short and focused
  • Pure Functions: Avoid side effects when possible
  • Clear Parameters: Use descriptive parameter names
// ✅ Good: Small, focused functions
function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount);
}

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function createUser(name, email) {
    if (!name || !email) {
        throw new Error('Name and email are required');
    }
    
    if (!validateEmail(email)) {
        throw new Error('Invalid email format');
    }
    
    return {
        id: Date.now(),
        name: name.trim(),
        email: email.toLowerCase(),
        createdAt: new Date()
    };
}

🔹 Code Comments and Documentation

Write helpful comments that explain why, not what:

// ✅ Good: Explains the reasoning
function debounce(func, delay) {
    let timeoutId;
    
    // Return a new function that delays execution
    // This prevents excessive API calls during rapid user input
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
}

// ✅ Good: Documents complex logic
function calculateShippingCost(weight, distance, isPriority) {
    const BASE_RATE = 5.00;
    const WEIGHT_MULTIPLIER = 0.50;
    const DISTANCE_MULTIPLIER = 0.10;
    const PRIORITY_SURCHARGE = 10.00;
    
    // Base calculation: fixed rate + weight factor + distance factor
    let cost = BASE_RATE + (weight * WEIGHT_MULTIPLIER) + (distance * DISTANCE_MULTIPLIER);
    
    // Add priority shipping surcharge if requested
    if (isPriority) {
        cost += PRIORITY_SURCHARGE;
    }
    
    return Math.round(cost * 100) / 100; // Round to 2 decimal places
}

// ❌ Bad: States the obvious
let x = 5; // Set x to 5
x++; // Increment x by 1

🧠 Test Your Knowledge

Which is the best way to declare a constant value?