Writing Readable JavaScript Code

A lot of times I have seen developers looking at the existing code base and say they can’t make sense of the existing code. If we keep a certain set of rules and standards in mind, we can write code which is easy to read and understand.

In this article, we’ll discuss about certain things that every web developer should keep in mind while developing web applications.

Write Meaningful If Conditions

Take a look at the below code statement,

parseGroup(grp:any){
  if(grp['id'] == 1){
    // code to parse info 
  } else if(grp['id'] == 2) {
    // code to parse info
  }
}

In the parseGroup method we are comparing the group id to a particular value and parsing accordingly. Now when someone new tries to understand the above code, he has no clue as to what is group with Id 1 or 2. It would be quite readable if instead of simply comparing group ids with numbers, we encapsulate it into another method.

parseGroup(grp:any){
  if(this.checkInClassA(grp['id'])){
    // code to parse info 
  } else if(this.checkInClassB(grp['id'])) {
    // code to parse info
  }
}

checkInClassA(grpId:Number){
  return grpId == 1;
}

checkInClassB(grpId:Number){
  return grpId == 2;
}

Write Meaningful Method Names

Method names should be such that we should be simply able to read the code in plain English. Take for example the following code,

parseGroup(grp:any){
  if(this.checkInClassA(grp['id'])){
    // code to parse info 
  } else if(this.checkInClassB(grp['id'])) {
    // code to parse info
  }
}

Here when we read if checkInClassA, we know that it will check in Class A. But it doesn’t offer much clarity. Let’s rename it groupInClassA.

parseGroup(grp:any){
  if(this.groupInClassA(grp['id'])){
    // code to parse info 
  } else if(this.groupInClassB(grp['id'])) {
    // code to parse info
  }
}

And now it flows along with the if statement and brings clarity to the readability of the code.

Function/Method Should Have a Single Purpose

If a method is named validateForm it should only validate the form inputs and not save the form. This is the most common thing I have seen developers do that they define a function and they do everything within the same method or function.

Every method or function should have a specific purpose. And when we write the application keeping that in mind, your code:

  • Is concise and clear
  • Easy to debug
  • Readable
  • Easy to modify
  • Easy to Unit test

Keep It Short

When you scroll and see a method stretching 100 lines of code, the visual itself is tiring.

I follow a rule of max 30 lines of code per method or function and try to break the long code into different meaningful methods. It keeps the code clear and easy to understand.

Wrapping it up

So I hope you enjoyed reading how to write readable code. Do let me know your thoughts via Twitter.