JavaScript Clean Code Tips And Best Practices

Complying with clean and designed code is imperative in current data and improvement advances. Moreover, since it makes your and others’ lives simpler to get, that same code in the future additionally makes a difference in creating a more professional computer program built in the industry. In this article, we have explained JavaScript clean code tips and best principles.

🔹Try Not To Nest Excessively

We compose code each time in a settled arrangement. So really, it does not influence anything off-base with it, but it makes it harder to peruse a code rather than in a straightforward way. We use the “return” explanation to settle this.

So it permits one in-case condition through which it is prepared to utilize it for checking blunders and returns some time recently executing advance code. So ready to avoid undesirable settlements with if/else articulations.

 //Bad Way
  function saveItem(item) {
    if (item != null) {
      console.log("Saving item");
      localStorage.setItem("USER_DETAILS", item)
    }
  }

  //Good Way
  function saveItem(item) {
    if (item == null) return;

    console.log("Saving item");
    localStorage.setItem("USER_DETAILS", item)
  }

Here I’m giving other illustrations also. So there’s nothing off-base with implementing that solution. But ready to alter its way, which can be exceptionally simple to execute.

//Bad Way
  function saveItem(item) {
    if (item != null) {
      console.log("Validating");

      if (item.isValid()) {
        console.log("Saving item");
        localStorage.setItem("USER_DETAILS", item)
      }
    }
  }
  //Good Way
  function saveItem(item) {
    if (item == null) return;

    console.log("Validating");
    if (!item.isValid) return;

    console.log("Saving item");
    localStorage.setItem("USER_DETAILS", item)
  }

🔹Utilize Object Destructuring For Function Parameterization

Suppose we have one function which accepts some arguments and returns some new values based on calculations. Mostly we are doing the below.

 //Bad Way
  function getFormattedDate(date) {
    const day = date.day;
    const month = date.month;
    const year = date.year;

    return `${day}/${month}/${year}`
  }

Next, we can do destructuring the object and use the parameters given below.

//Good Way
  function getFormattedDate(date) {
    const { day, month, year } = date;

    return `${day}/${month}/${year}`
  }

So now we can do further if we can destructure the parameters directly and remove the unwanted code like the given below.

 //More Better Way
  function getFormattedDate({ day, month, year }) {
    return `${day}/${month}/${year}`
  }

🔹Keep Your Functions Simple

When we write a function writing all functionality in one block, it’s not a good way. It helps to create bugs in code. So a better approach is dividing your functionality into multiple methods per requirements.

  //Bad Way
  function loginAndValidate() {

  }

  //Good Way
  function validate() { }
  function login() { }

🔹Use Meaningful Variable Names At All Times

When we are coding, we give variables and methods names randomly without hesitation. But it’s not a good way to do that as a developer. So we always have to use variable and method names in a meaningful manner.

1. When we use functions, we use verbal names for their declaration.

//Bad Way
 function credentialValidation() { }

 //Good Way
 function validateCredentials() { }

2. When we know that method’s return type will be Boolean, then use is a word in the variable declaration.

 //Good Way
 const isValidEmail = validateCredentials()

3. When we use any loops or inbuilt function of JS, use the proper name for its variable iteration. And also use plurals for the array declaration.

//Bad Way
const user = [
     { name: "John", age: 24, },
     { name: "Max", age: 30, },
     { name: "Denial", age: 26, }
]

//Good Way
const users = [
     { name: "John", age: 24, },
     { name: "Max", age: 30, },
     { name: "Denial", age: 26, }
]

//Bad Way
users.map((a) => {
  console.log(a);
})

//Good Way
users.map((user) => {
  console.log(users);

})

🔹Try To Use Ternary Operator

The ternary operator is a very popular shorthand operator used in coding languages. We can use it instead of traditional if/else statements.

 //Bad Way
   let age = 16;
   if (age < 18) {
     return "MINOR";
   }
   else {
     return "ADULT";
   }

   //Good Way
   let age = 16;
   return age < 18 ? "MINOR" :"ADULT";

🔹Use Optional Chaining

We mostly use Dot notation to access the key value from an object. This thing is valid, but we can use the optional chaining feature for advanced. For example, we can use it when we exactly don’t know about the required key. So by using it, we can get value if the key exists. Otherwise, we will get an undefined value.

const data = {
     users: [
       'John',
       'Miya'
     ]
   }

   // Bad Way
   if (data.users && data.users.length >= 2) {
     console.log('2nd value in users: ', data.users[1])
   }
   // Good Way
   console.log('2nd value in users: ', data?.users?.[1]) // 'John'
   console.log('3rd value in users: ', data?.users?.[2]) // undefined

🔹Use Spread Operator

We are using the concat or object.assign() method to merge an array or object into another one. But we can use the Spread (…) operator instead.

  // Bad Way
   const schoolMarks = [30, 40, 50]
   const collageMarks = [50, 60, 70].concat(schoolMarks)

   const schoolStudent = { name: "John" }
   const collageStudent = Object.assign(schoolStudent, { age: 18 })


   // Good Way
   const schoolMarks = [30, 40, 50]
   const collageMarks = [50, 60, 70,...schoolMarks]

   const schoolStudent = { name: "John" }
   const collageStudent = { ...schoolStudent, age: 18 }

🔹Avoid Branching And Make A Quick Return

When writing code, we put conditions based on requirements using if/else statements. Instead of it, try to use code in a simple and less complex way that returns value quickly. It can be easy to read and reliable.

//Bad Way
   function validateCredentials() {
     const email = "";
     if (email) {
       if (email.isValid()) {
         console.log("Email is valid");
       }
       else {
         throw new Error("Enter valid email")
       }
     }
     else {
       throw new Error("Enter email")
     }
   }

   //Good Way
   function validateCredentials() {
     const email = "";
     if (!email) throw new Error("Enter email");
     if (!email.isValid()) throw new Error("Enter valid email")
     console.log("Email is valid");
   }

🔹Maintain A Strategic Distance From Callbacks

Traditional nested callbacks are not looking good as compared to the current new features given by ES. On the other hand, new Promises and try/catch have cleaner and linear code with better solutions.

 //Bad Way
   getUser(function (err, user) {
     getUserProfile(user, function (err, profile) {
       getPremiumFeature(profile, function (err, results) {
         setUnlockFeature(results, function (err, data) {
           console.error(err);
         })
       })
     })
   })

   //Good Way
   getUser()
     .then(getUserProfile)
     .then(getPremiumFeature)
     .then(setUnlockFeature)
  .catch((err) => console.error(err));

   //or using Async/Await
   async function sendUserStatistics() {
     try {
       const user = await getUser();
       const profile = await getUserProfile(user);
       const results = await getPremiumFeature(profile);
       return setUnlockFeature(results);
     } catch (err) {
       console.error(err);
     }
   }

🔹User Arrow Functions

While writing code, we use traditional functions for implementing any feature. But the new ES has an Arrow function feature which can be more productive and easy to use.

While we have small code based on logic, we have to return something we can use because the Arrow function has a shorter syntax. Because by using the arrow function, we can return value without the return keyword.

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

   //Good Way
   const sum = (a, b) => a + b;
coma

Conclusion

We must write clean and readable code when developing anything in JavaScript or any other language. Here I have given some examples of how to write JavaScript clean code. Writing this kind of code is the best practice for making any product good, bug-free, more smooth in performance and easy to maintain by us or by others also.

Ronak K

React-Native Developer

Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!