DEV Community

Cover image for Top 10 JavaScript Best Practices for Writing Clean Code 🚀
Dipak Ahirav
Dipak Ahirav

Posted on • Edited on

Top 10 JavaScript Best Practices for Writing Clean Code 🚀

Writing clean, maintainable JavaScript code is essential for creating scalable applications and collaborating effectively with other developers. Here are ten best practices to help you write clean JavaScript code. 🌟

please subscribe to my YouTube channel to support my channel and get more web development tutorials.

1. Use Meaningful Variable and Function Names 📝

Choosing meaningful and descriptive names for your variables and functions makes your code easier to understand and maintain. Avoid using single-letter names or abbreviations that may confuse other developers.

Example:

// Poor naming
let a = 5;
let b = 10;
function c(x, y) {
  return x + y;
}

// Good naming
let width = 5;
let height = 10;
function calculateArea(width, height) {
  return width * height;
}
Enter fullscreen mode Exit fullscreen mode

2. Keep Functions Small and Focused 🎯

Small, focused functions that perform a single task are easier to test, debug, and maintain. Aim to write functions that do one thing and do it well.

Example:

// Large, unfocused function
function processUserData(user) {
  // Validate user data
  if (!user.name || !user.email) {
    throw new Error('Invalid user data');
  }
  // Save user to database
  database.save(user);
  // Send welcome email
  emailService.sendWelcomeEmail(user.email);
}

// Small, focused functions
function validateUserData(user) {
  if (!user.name || !user.email) {
    throw new Error('Invalid user data');
  }
}

function saveUserToDatabase(user) {
  database.save(user);
}

function sendWelcomeEmail(email) {
  emailService.sendWelcomeEmail(email);
}

function processUserData(user) {
  validateUserData(user);
  saveUserToDatabase(user);
  sendWelcomeEmail(user.email);
}
Enter fullscreen mode Exit fullscreen mode

3. Use Consistent Coding Style 🌐

A consistent coding style helps make your code more readable and maintainable. Use tools like ESLint and Prettier to enforce a consistent style across your codebase.

Example (ESLint configuration):

{
  "extends": "eslint:recommended",
  "env": {
    "browser": true,
    "es6": true
  },
  "rules": {
    "indent": ["error", 2],
    "quotes": ["error", "single"],
    "semi": ["error", "always"]
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Comment and Document Your Code 📜

Adding comments and documentation to your code helps other developers (and your future self) understand its purpose and functionality. Use comments to explain why certain decisions were made, and document your functions and modules.

Example:

/**
 * Calculate the area of a rectangle.
 * @param {number} width - The width of the rectangle.
 * @param {number} height - The height of the rectangle.
 * @return {number} The area of the rectangle.
 */
function calculateArea(width, height) {
  return width * height;
}

// This function processes user data by validating it,
// saving it to the database, and sending a welcome email.
function processUserData(user) {
  validateUserData(user);
  saveUserToDatabase(user);
  sendWelcomeEmail(user.email);
}
Enter fullscreen mode Exit fullscreen mode

5. Avoid Magic Numbers and Strings 🎩

Magic numbers and strings are hard-coded values that lack context and can make your code harder to understand and maintain. Use constants or enums to give these values meaningful names.

Example:

// Using magic numbers
function calculateDiscount(price) {
  return price * 0.1;
}

// Using constants
const DISCOUNT_RATE = 0.1;

function calculateDiscount(price) {
  return price * DISCOUNT_RATE;
}

// Using enums for better readability
const UserRole = {
  ADMIN: 'admin',
  USER: 'user',
  GUEST: 'guest'
};

function checkAccess(role) {
  if (role === UserRole.ADMIN) {
    // Allow access
  }
}
Enter fullscreen mode Exit fullscreen mode

6. Use let and const Instead of var 🚫

Avoid using var to declare variables. Instead, use let and const to ensure block-scoping and avoid hoisting issues. This helps prevent unexpected behavior and makes your code more predictable.

Example:

let name = 'John';
const age = 30;
Enter fullscreen mode Exit fullscreen mode

7. Avoid Using eval()

The eval() function executes a string as JavaScript code, which can lead to security vulnerabilities and performance issues. Avoid using eval() whenever possible.

Example:

// Avoid this
eval('console.log("Hello, World!")');

// Use this instead
console.log('Hello, World!');
Enter fullscreen mode Exit fullscreen mode

8. Handle Errors Gracefully 🌟

Handling errors properly ensures that your application can gracefully recover from unexpected situations. Use try-catch blocks and proper error logging.

Example:

function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch error:', error);
    throw error; // Re-throw the error after logging it
  }
}
Enter fullscreen mode Exit fullscreen mode

9. Use Promises and Async/Await for Asynchronous Code 🌐

Promises and async/await make asynchronous code easier to write and understand. Avoid callback hell by using these modern JavaScript features.

Example:

// Using Promises
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// Using async/await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
Enter fullscreen mode Exit fullscreen mode

10. Write Unit Tests 🧪

Writing unit tests ensures that your code behaves as expected and makes it easier to catch bugs early. Use testing frameworks like Jest, Mocha, or Jasmine to write and run your tests.

Example (Jest):

// Function to test
function sum(a, b) {
  return a + b;
}

// Test
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});
Enter fullscreen mode Exit fullscreen mode

Start Your JavaScript Journey

If you're new to JavaScript or want a refresher, visit my blog on BuyMeACoffee to get started with the basics.

👉 Introduction to JavaScript: Your First Steps in Coding

Support My Work

If you enjoy my content and want to support my work, consider buying me a coffee! Your support helps me continue creating valuable content for the developer community.

By following these best practices, you can write cleaner, more maintainable JavaScript code that is easier to understand and work with. Happy coding! ✨

Series Index

Part Title Link
1 Ditch Passwords: Add Facial Recognition to Your Website with FACEIO Read
2 Top 4 JavaScript Debugging Tips for Beginners🐞 Read
3 Top 20 JavaScript Tricks and Tips for Every Developer 🚀 Read
4 8 Exciting New JavaScript Concepts You Need to Know Read
5 Top 7 Tips for Managing State in JavaScript Applications Read
6 🔒 Essential Node.js Security Best Practices Read
7 10 Best Practices for Optimizing Angular Performance Read
8 Top 10 React Performance Optimization Techniques Read
9 Top 15 JavaScript Projects to Boost Your Portfolio Read
10 6 Repositories To Master Node.js Read
11 Best 6 Repositories To Master Next.js Read
12 Top 5 JavaScript Libraries for Building Interactive UI Read
13 Top 3 JavaScript Concepts Every Developer Should Know Read
14 20 Ways to Improve Node.js Performance at Scale Read
15 Boost Your Node.js App Performance with Compression Middleware Read
16 Understanding Dijkstra's Algorithm: A Step-by-Step Guide Read
17 Understanding NPM and NVM: Essential Tools for Node.js Development Read

Follow and Subscribe:

Top comments (6)

Collapse
 
arjunbroepic profile image
Arjun S

I would not write those small functions (except for the validation function). As a matter of fact, the new functions might be more harder to read than just using the existing methods. Functions that are too small, like wrappers for one single method line small, can be bad too.

And also, enums are great, but if you use TypeScript, a better way would be to just use literal strings.

Collapse
 
kocreative profile image
Kat

Thanks for this! It's very clear and some great advice :)

Collapse
 
dipakahirav profile image
Dipak Ahirav

Thanks for the feedback @kocreative

Collapse
 
mexikode profile image
MexiKode ⚙

one line functions are never recommended (specially if a method to handle the operation already exists)

function outputResultIntoTheConsolePlease(item){
   console.log(item);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
moshe_h_m profile image
MosheHaimMakias

Why should we throw an error after catching it, this makes no sense.

Collapse
 
jangelodev profile image
João Angelo

Hi Dipak Ahirav,
Top, very nice and helpful !
Thanks for sharing.