DEV Community

Cover image for Mastering JavaScript: 10 Best Practices for Writing Clean Code
Asima Chowdhury
Asima Chowdhury

Posted on

Mastering JavaScript: 10 Best Practices for Writing Clean Code

As JavaScript continues to dominate the web development world 🌐, writing clean, maintainable code is crucial for long-term success. πŸ› οΈ Whether you're a beginner or have some experience under your belt, following best practices ensures your code is understandable, scalable, and bug-free.✨ In this post, we'll go through 10 essential JavaScript best practices that will level up your coding game! πŸš€πŸ’»

1. Use Meaningful Variable and Function Names

Naming is one of the most important parts of writing clean code. Avoid cryptic variable names like x, y, or tempβ€”instead, make your variable and function names descriptive.

// Bad Example
let x = 10;
function calc(a, b) {
  return a + b;
}

// Good Example
let itemCount = 10;
function calculateTotal(price, tax) {
  return price + tax;
}
Enter fullscreen mode Exit fullscreen mode

2. Use const and let Instead of var

The var keyword has function scope, which can lead to bugs. In modern JavaScript, it's better to use const for constants and let for variables that need to change.

// Bad Example (using var)
var name = 'John';
name = 'Jane';

// Good Example (using const and let)
const userName = 'John';
let userAge = 30;
Enter fullscreen mode Exit fullscreen mode

3. Avoid Global Variables

Minimize the use of global variables as they can lead to conflicts and hard-to-debug code. Keep your variables local whenever possible.

// Bad Example (Global variable)
userName = 'John';

function showUser() {
  console.log(userName);
}

// Good Example (Local variable)
function showUser() {
  const userName = 'John';
  console.log(userName);
}
Enter fullscreen mode Exit fullscreen mode

4. Write Short, Single-Responsibility Functions

Functions should do one thing and do it well. This practice makes your code easier to test, debug, and maintain.

Bad Example (doing too much in one function):

function processOrder(order) {
  let total = order.items.reduce((sum, item) => sum + item.price, 0);
  if (total > 100) {
    console.log('Free shipping applied!');
  }
  console.log('Order total:', total);
}
Enter fullscreen mode Exit fullscreen mode

This function is calculating the total and also checking for free shipping, which are two different responsibilities.

Good Example (separate responsibilities):

function calculateTotal(order) {
  return order.items.reduce((sum, item) => sum + item.price, 0);
}

function checkFreeShipping(total) {
  if (total > 100) {
    console.log('Free shipping applied!');
  }
}

function processOrder(order) {
  const total = calculateTotal(order);
  checkFreeShipping(total);
  console.log('Order total:', total);
}
Enter fullscreen mode Exit fullscreen mode

In the good example, the responsibilities are split into three smaller functions:

  • calculateTotal handles only the calculation.
  • checkFreeShipping determines if shipping is free.
  • processOrder coordinates these functions, making the code easier to manage.

5. Use Arrow Functions for Simple Callbacks

Arrow functions provide a concise syntax and handle the this keyword better in many situations, making them ideal for simple callbacks.

// Bad Example (using function)
const numbers = [1, 2, 3];
let squares = numbers.map(function (num) {
  return num * num;
});

// Good Example (using arrow function)
let squares = numbers.map(num => num * num);
Enter fullscreen mode Exit fullscreen mode

6. Use Template Literals for String Interpolation

Template literals are more readable and powerful than string concatenation, especially when you need to include variables or expressions inside a string.

// Bad Example (string concatenation)
const user = 'John';
console.log('Hello, ' + user + '!');

// Good Example (template literals)
console.log(`Hello, ${user}!`);
Enter fullscreen mode Exit fullscreen mode

7. Use Destructuring for Objects and Arrays

Destructuring is a convenient way to extract values from objects and arrays, making your code more concise and readable.

// Bad Example (no destructuring)
const user = { name: 'John', age: 30 };
const name = user.name;
const age = user.age;

// Good Example (with destructuring)
const { name, age } = user;
Enter fullscreen mode Exit fullscreen mode

8. Avoid Using Magic Numbers

Magic numbers are numeric literals that appear in your code without context, making the code harder to understand. Instead, define constants with meaningful names.

// Bad Example (magic number without context)
function calculateFinalPrice(price) {
  return price * 1.08; // Why 1.08? It's unclear.
}

// Good Example (use constants with meaningful names)
const TAX_RATE = 0.08; // 8% sales tax

function calculateFinalPrice(price) {
  return price * (1 + TAX_RATE); // Now it's clear that we are adding tax.
}
Enter fullscreen mode Exit fullscreen mode

9. Handle Errors Gracefully with try...catch

Error handling is essential for writing robust applications. Use try...catch blocks to manage errors and avoid program crashes.

// Bad Example (no error handling)
function parseJSON(data) {
  return JSON.parse(data);
}

// Good Example (with error handling)
function parseJSON(data) {
  try {
    return JSON.parse(data);
  } catch (error) {
    console.error('Invalid JSON:', error.message);
  }
}
Enter fullscreen mode Exit fullscreen mode

10. Write Comments Wisely

While your code should be self-explanatory, comments can still be helpful. Use them to explain why something is done a certain way, rather than what is happening.

// Bad Example (obvious comment)
let total = price + tax; // Adding price and tax

// Good Example (helpful comment)
// Calculate the total price with tax included
let total = price + tax;
Enter fullscreen mode Exit fullscreen mode

Following these best practices will help you write cleaner, more maintainable JavaScript code. ✨ Whether you're just starting out or looking to refine your skills, incorporating these tips into your workflow will save you time and headaches in the long run. πŸ’‘πŸš€

Happy coding!πŸ’»

Top comments (1)

Collapse
 
charles_roth_8c0df94d211a profile image
Charles Roth • Edited

(2) needs A LOT more explanation. Using var intentionally for function scope is a GOOD idea. Make it clearer where (and why!) const, let, and var should be used.

(10) Saying "write comments wisely" provides no useful information. Define what "wisely" means!
In ANY language, a block of comments at the top of a class/module/package/whatever is really helpful, if it describes WHY this class (etc.) exists, what problem it's meant to solve. Basic context for the first time reader/modifier of the class (etc).

If I find myself writing comments to explain HOW something works, then my first step is refactor the code to use more meaningful variable and function names, and possibly break it into smaller pieces (functions) where the names can identify the purpose of each chunk of code. Only in cases where that's not sufficient, will I then add comments to explain the "how".