logo
Published on

Seven Tips for Writing Clean JavaScript Code

Table of Contents

Introduction

As JavaScript continues to grow in popularity, it is important for developers to write clean and efficient code that is easy to read and maintain. In this blog post, we will discuss best practices for writing clean and efficient JavaScript code.

Tips

1. Use Descriptive Variable and Function Names

One of the most important aspects of writing clean code is using descriptive variable and function names. Names that are too short or too long can be confusing to other developers and make the code harder to read. Descriptive names help to make the code more readable and can reduce the amount of time it takes to understand what the code is doing.

// Bad example
let x = 10;
let y = 20;

function z(a, b) {
  return a + b;
}

// Good example
let width = 10;
let height = 20;

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

2. Avoid Global Variables

Global variables should be avoided as much as possible. They can cause naming conflicts and make it difficult to maintain the code. Instead, use local variables and pass them between functions as needed. This can help to reduce the amount of memory used by the program and make the code more efficient.

// Bad example
let total = 0;

function calculateSum(num1, num2) {
    total = num1 + num2;
}

calculateSum(5, 10);
console.log(total); // Output: 15
// Good example
function calculateSum(num1, num2) {
    // we can return the total here but for demonstration purposes we make a variable
    const total = num1 + num2;

    return total;
}

const sum = calculateSum(5, 10);
console.log(sum); // Output: 15

3. Use Comments

Comments can be used to explain what the code is doing and why it is doing it. This can make the code easier to understand and maintain, especially for other developers who may not be familiar with the code. However, too many comments can make the code harder to read, so it is important to use them sparingly.

// Bad example - Comments stating the obvious
let total = 0; // Set total to 0
for (let i = 0; i < items.length; i++) { // Loop through items
  total += items[i].price; // Add item price to total
}
// Calculate tax
const tax = total * 0.1; // Multiply total by tax rate
// Calculate final price
const finalPrice = total + tax; // Add tax to total
// Good example - Comments that provide context and explain why the code is doing what it does
const total = 0;
for (let i = 0; i < items.length; i++) {
  total += items[i].price; // Add current item's price to total
}

// Calculate tax at a rate of 10%
const tax = total * 0.1;
// Calculate final price by adding total and tax
const finalPrice = total + tax;

4. Use Proper Indentation and Formatting

Proper indentation and formatting can make the code easier to read and maintain. Consistent indentation and formatting can also make it easier to identify errors in the code.

function calculateTotal(price, quantity) {
  let total = price * quantity;

  if (total > 100) {
    total *= 0.9;
    console.log("Discount applied!");
  }

  return total;
}

5. Use Strict Mode

Strict mode is a feature that was introduced in ECMAScript 5. It is a way to enforce stricter rules on the code, which can help to identify errors and prevent common programming mistakes. It can also make the code more efficient by reducing the number of errors that occur during runtime.

"use strict";

function calculateTotal(price, quantity) {
  total = price * quantity;
  if (total > 100) {
    total *= 0.9;
    console.log("Discount applied!");
  }
  return total;
}

console.log(calculateTotal(10, 5)); // Should output 50

In the above example, the "use strict"; statement is included at the top of the file to enable strict mode. In this case, strict mode catches the mistake of using an undeclared variable total, which would normally be allowed in non-strict mode. This helps ensure that the code is more reliable and less error prone.

6. Avoid Unnecessary Loops

Loops can be very resource-intensive, especially if they are used excessively or unnecessarily. It is important to avoid unnecessary loops and to optimize loops where possible. This can help to reduce the amount of time it takes for the code to run and make it more efficient.

// Bad example - using nested loops to check if two arrays have common elements
function hasCommonElements(arr1, arr2) {
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                return true;
            }
        }
    }

    return false;
}

// Good example - using Array.includes() to check if two arrays have common elements
function hasCommonElements(arr1, arr2) {
    for (let i = 0; i < arr1.length; i++) {
        // technically will use a loop underneath but it is unecessary to create our own
        if (arr2.includes(arr1[i])) {
            return true;
        }
    }

    return false;
}

7. Use Modern JavaScript features

Modern JavaScript features, such as arrow functions, template literals, and destructuring, can make the code more efficient and easier to read. It is important to stay up-to-date with the latest JavaScript features and to use them where appropriate.

// Bad example - using var to declare variables
var name = "John";
var age = 25;

// Good example - using let and const to declare variables
const name = "John";
let age = 25;

// Bad example - using for loop to iterate over an array
const numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

// Good example - using forEach() method to iterate over an array
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));

// Bad example - using function expressions
const sum = function(a, b) {
  return a + b;
};

// Good example - using arrow functions
const sum = (a, b) => a + b;

// Bad example - using callbacks for asynchronous operations
setTimeout(function() {
  console.log("Hello, world!");
}, 1000);

// Good example - using Promises or async/await for asynchronous operations
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function example() {
  await wait(1000);
  console.log("Hello, world!");
}

Conclusion

By following these best practices, developers can write clean and efficient JavaScript code that is easy to read and maintain. Using descriptive variable and function names, avoiding global variables, using comments, proper indentation and formatting, using strict mode, avoiding unnecessary loops, and using modern JavaScript features can all contribute to writing efficient and effective JavaScript code.