Codeskill

Learn to code, step by step

JavaScript Best Practices: Writing Clean and Efficient Code

Good habits make JavaScript easier to read, debug, and maintain. This page lists practical best practices you can apply straight away.

1. Use meaningful variable names

Variable names should tell you what they hold. Descriptive names save you (and everyone else) time later.

Bad practice:

let d = new Date();

Good practice:

let currentDate = new Date();

2. Stick to a consistent coding style

Pick a style for naming, indentation, and bracket placement – then stick to it. Consistency makes code easier to scan.

Example – consistent style:

// Consistent use of camelCase and indentation
function calculateArea(width, height) {
    return width * height;
}

3. Avoid global variables

Global variables cause conflicts and unpredictable behaviour, especially in larger apps. Declare variables in the scope where they are needed.

Bad practice:

let name = 'Alice';

Good practice:

function greet() {
    let name = 'Alice';
    console.log(name);
}

4. Use functions and modules to organise code

Break code into reusable functions and modules. That makes it easier to read, debug, and maintain.

Example – modular code:

// utils.js
export function sum(a, b) {
    return a + b;
}

// app.js
import { sum } from './utils.js';
console.log(sum(5, 10));

5. Prefer const and let over var

ES6 introduced let and const for block-level scoping. var is function-scoped and is best avoided in new code.

Example – using let and const:

const MAX_USERS = 100;
let currentUsers = 0;

6. Use arrow functions for shorter syntax

Arrow functions are shorter to write and do not bind their own this, which is useful in certain contexts.

Example – arrow function:

const greet = name => `Hello, ${name}!`;

7. Keep functions focused

Each function should do one thing. If it is doing too much, split it into smaller functions.

Example – single responsibility:

function calculateArea(width, height) {
    return width * height;
}

function calculatePerimeter(width, height) {
    return 2 * (width + height);
}

8. Use template literals for string concatenation

Template literals are more readable than chaining strings with +.

Example – template literals:

const greeting = `Hello, ${name}! Welcome to the site.`;

9. Handle errors gracefully

Use try-catch blocks where things can go wrong, and log meaningful error messages.

Example – error handling:

try {
    // Code that may throw an error
} catch (error) {
    console.error("Error encountered:", error);
}

10. Avoid deep nesting

Deeply nested code is hard to follow. Flatten structures where you can.

Bad practice:

if (condition1) {
    if (condition2) {
        // Deep nesting
    }
}

Good practice:

if (condition1 && condition2) {
    // Flattened structure
}

11. Comment wisely

Comments should explain why something is done, not what the code already makes obvious.

Example – good commenting:

// Using regex to validate email format
const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

12. Test your code

Test your code – manually or with automated tests – to make sure it behaves as expected.

Example – basic testing:

console.assert(sum(2, 2) === 4, "The sum function works correctly");

None of this is complicated, but it adds up. Write code that humans can read as easily as the computer can run it.

PreviousWorking with JSON in JavaScript