DEV Community

Cover image for Best Practices for Writing Clean and Maintainable Code in JavaScript
Christopher Glikpo  ⭐
Christopher Glikpo ⭐

Posted on

Best Practices for Writing Clean and Maintainable Code in JavaScript

Clean and maintainable code is crucial for the long-term success and scalability of any software project. It improves collaboration among team members, reduces the likelihood of bugs, and makes code easier to understand, test, and maintain. In this blog post, we will explore some best practices for writing clean and maintainable code in JavaScript, along with code examples to illustrate each practice.

1. Consistent Code Formatting:

Consistent code formatting is essential for readability. It helps developers understand the code faster and improves collaboration. Use a consistent and widely accepted code style guide, such as the one provided by ESLint, and configure your editor or IDE to automatically format the code accordingly.
Example:

// Bad formatting
function calculateSum(a,b){
    return a + b;
}

// Good formatting
function calculateSum(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

2. Descriptive Variable and Function Names:

Use descriptive and meaningful names for variables, functions, and classes. Avoid single-letter variable names or abbreviations that might confuse others. This practice enhances code readability and reduces the need for comments.
Example:

// Bad naming
const x = 5;

// Good naming
const numberOfStudents = 5;
Enter fullscreen mode Exit fullscreen mode

3. Modularity and Single Responsibility Principle:

Follow the principle of Single Responsibility for functions and classes. Each function or class should have a single, well-defined responsibility. This approach improves code reusability and makes it easier to test, debug, and maintain.
Example:

// Bad practice
function calculateSumAndAverage(numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
  }
  const average = sum / numbers.length;
  return [sum, average];
}

// Good practice
function calculateSum(numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
  }
  return sum;
}

function calculateAverage(numbers) {
  const sum = calculateSum(numbers);
  const average = sum / numbers.length;
  return average;
}
Enter fullscreen mode Exit fullscreen mode

4. Avoid Global Variables:

Minimize the use of global variables as they can lead to naming conflicts and make the code harder to reason about. Instead, encapsulate your code in functions or modules and use local variables whenever possible.
Example:

// Bad practice
let count = 0;

function incrementCount() {
  count++;
}

// Good practice
function createCounter() {
  let count = 0;

  function incrementCount() {
    count++;
  }

  return {
    incrementCount,
    getCount() {
      return count;
    }
  };
}

const counter = createCounter();
counter.incrementCount();
Enter fullscreen mode Exit fullscreen mode

5. Error Handling and Robustness:

Handle errors gracefully and provide meaningful error messages or log them appropriately. Validate inputs, handle edge cases, and use proper exception handling techniques such as try-catch blocks.
Example:

// Bad practice
function divide(a, b) {
  return a / b;
}

// Good practice
function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

try {
  const result = divide(10, 0);
  console.log(result);
} catch (error) {
  console.error(error.message);
}
Enter fullscreen mode Exit fullscreen mode

6. Avoid Code Duplication:

Code duplication not only leads to bloated code but also makes maintenance and bug fixing more challenging. Encapsulate reusable code into functions or classes and strive for a DRY (Don't Repeat Yourself) approach. If you find yourself copying and pasting code, consider refactoring it into a reusable function or module.
Example:

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

function calculatePerimeterOfRectangle(length, width) {
  return 2 * (length + width);
}

// Good practice
function calculateArea(length, width) {
  return length * width;
}

function calculatePerimeter(length, width) {
  return 2 * (length + width);
}
Enter fullscreen mode Exit fullscreen mode

7. Use Comments Wisely:

While clean code should be self-explanatory, there are cases where comments are necessary to provide additional context or clarify complex logic. Use comments sparingly and make them concise and meaningful. Focus on explaining the "why" rather than the "how."
Example:

// Bad practice
function calculateTotalPrice(products) {
  // Loop through products
  let totalPrice = 0;
  for (let i = 0; i < products.length; i++) {
    totalPrice += products[i].price;
  }
  return totalPrice;
}

// Good practice
function calculateTotalPrice(products) {
  let totalPrice = 0;
  for (let i = 0; i < products.length; i++) {
    totalPrice += products[i].price;
  }
  return totalPrice;
  // The total price is calculated by summing up the prices of all the products in the array.
}
Enter fullscreen mode Exit fullscreen mode

8. Optimize Performance:

Efficient code improves the overall performance of your application. Be mindful of unnecessary computations, excessive memory usage, and potential bottlenecks. Use appropriate data structures and algorithms to optimize performance. Profile and measure your code using tools like the Chrome DevTools to identify performance issues and address them accordingly.
Example:

// Bad practice
function findItemIndex(array, target) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === target) {
      return i;
    }
  }
  return -1;
}

// Good practice
function findItemIndex(array, target) {
  let left = 0;
  let right = array.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (array[mid] === target) {
      return mid;
    }

    if (array[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1;
}
Enter fullscreen mode Exit fullscreen mode

9. Write Unit Tests:

Unit testing is essential for ensuring the correctness and maintainability of your code. Write automated tests to cover different scenarios and edge cases. This helps catch bugs early, facilitates code refactoring, and gives confidence in modifying existing code. Use testing frameworks like Jest or Mocha for writing and running tests.
Example (using Jest):

// Code
function sum(a, b) {
  return a + b;
}

// Test
test('sum function adds two numbers correctly', () => {
  expect(sum(2, 3)).toBe(5);
  expect(sum(-1, 5)).toBe(4);
  expect(sum(0, 0)).toBe(0);
});
Enter fullscreen mode Exit fullscreen mode

10. Use Functional Programming Concepts:

Functional programming concepts, such as immutability and pure functions, can make your code more predictable and easier to reason about. Embrace immutable data structures and avoid mutating objects or arrays whenever possible. Write pure functions that have no side effects and produce the same output for the same input, making them easier to test and debug.
Example:

// Bad practice
let total = 0;

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

// Good practice
function addToTotal(total, value) {
  return total + value;
}
Enter fullscreen mode Exit fullscreen mode

11. Document your code with JSDoc

Use JSDoc to document your functions, classes, and modules. This helps other developers understand your code and makes it easier to maintain.

/**
 * Adds two numbers together.
 * @param {number} a - The first number.
 * @param {number} b - The second number.
 * @returns {number} The sum of the two numbers.
 */
function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

12. Use linters and formatters

Use tools like ESLint and Prettier to enforce consistent code style and catch potential issues before they become problems.

// .eslintrc.json
{
  "extends": ["eslint:recommended", "prettier"],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Writing clean and maintainable code is not just a matter of personal preference; it is a professional responsibility. By following the best practices outlined in this blog post, you can improve the quality of your JavaScript code, make it easier to understand, maintain, and collaborate on, and ensure the long-term success of your software projects. Consistency, readability, modularity, and error handling are key principles to keep in mind when striving for clean and maintainable code. Happy coding!

Top comments (7)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Some good tips here, but I'm not sure about a few of them...

4's Bad Practice is totally fine if it's declared in a module.

6 is very strange - why call it calculateArea rather than calculateAreaOfRectangle - that's what the function is doing, it's not calculating the area of any other shape properly. Calling it calculateArea is very confusing for a developer coming along later - for instance calculating the area of an ellipse can take the same parameters but yields a very different result.

8 is questionable as you don't point out that for your Good Practice the array should be sorted in the order of the search term, that's not a guaranteed good solution - what happens if the array is in the order of time, but that's not what you are searching for? What happens if you are only looking for 1 index once ever, why take the effort of sorting the array first?

Collapse
 
wizdomtek profile image
Christopher Glikpo ⭐

Let me address each of them:

  1. Using global variables even within a module can still introduce potential issues, such as naming conflicts and unintended side effects. While encapsulating code within modules can provide some level of organization and scoping, it's generally considered a best practice to minimize the use of global variables whenever possible. Instead, it's recommended to use local variables and explicitly pass any necessary data as function arguments or module dependencies.

  2. You make a valid point about the naming of the calculateArea function. It's important to choose descriptive names that accurately reflect the purpose of the function. In cases where the function specifically calculates the area of a rectangle, a more appropriate name would indeed be calculateAreaOfRectangle. The main idea is to choose names that convey the intended functionality and make the code more readable for future developers.

  3. You are correct that the binary search example I provided assumes a sorted array. I apologize for not clarifying that in the example. Sorting the array is indeed a prerequisite for using a binary search algorithm effectively. If the array is not sorted or the order is not relevant, using a binary search may not be appropriate. It's important to consider the specific requirements and constraints of your scenario before applying any algorithm. Additionally, there are alternative search algorithms, such as linear search, that may be more suitable for unsorted arrays or cases where sorting is not feasible or necessary.

Thank you for bringing these points to my attention. It's essential to critically evaluate and adapt best practices based on the specific context and requirements of your codebase. The goal is to strike a balance between following general best practices and tailoring them to suit the unique needs of your project.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Just on your 1st point, in a module they are specifically not global variables, they are module level variables inaccessible from any other scope unless explicitly exported and imported. It's very similar scoping to the example you give with a function.

Thread Thread
 
wizdomtek profile image
Christopher Glikpo ⭐

You're absolutely right, thank you

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

Hm. 8 and 10 contradict each other (especially) in Javascript. Things like map, find and reduce tend to be slower than just using a for loop (however optimisations in the engine can have surprising effects). Especially when treating everything as immutable... just mutating an array or object is certainly much faster than to create a new one on each iteration.

Collapse
 
anderspersson profile image
Anders Persson

Great list, think it apply to any language. !

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍