Some Ways to Write More Readable Code in JavaScript/Node.js

Some Ways to Write More Readable Code in JavaScript/Node.js

The Issue

What I believe many programmers aspire to is writing code that is easy to read and understand. There is plenty of evidence, such as the numerous Design Patterns that have been introduced to guide people in solving problems the way many still do. However, that's not all there is to it. Writing comprehensive code depends on each individual programmer.

We have various tools to aid in source code editing in many ways, such as formatting, colors, display interfaces, debugging support, allowing us to choose according to our preferences or collaborate with teams. In addition, there are still rules in place for team members to adhere to. Setting aside the formatting issue, today let's explore if there's a way to write code that's easier to read!

Some Ways to Make Code More Readable

Typically, those who write hard-to-maintain code often embody the Ninja style, which I have a detailed article on, Mentioning Ninja Code - Who are they that make many people "fearful"?. To write readable code, in addition to "putting away the sword" from the ninja, here are some ways you can consider from me.

Variable and Function Names

Variables and functions are the two most basic and important components of any program. Giving them understandable names is crucial for code readability.

There are many naming conventions for variables and functions that you can find on the internet. For example, I often name variables in camelCase style, using nouns related to the content they hold. Variables that are constants or only change with the environment are written in uppercase. Function names are verbs, using camelCase style as well. The function's purpose is reflected in its name, and it should only perform one task. If there are more tasks, split them into smaller functions.

Avoid Magic Numbers or Hardcoded Values

Occasionally, in code, you'll come across comparisons like this:

if (user.lastSeen < 4321)

Here, 4321 is referred to as a Magic Number or Hardcoded Value. We don't know exactly what this number represents because it doesn't have a name. This can confuse readers of the code. Instead, use a variable to represent the meaning of these numbers:

const timeActive = 4321;
if (timeExpired < timeActive)

Conditional Statements

It's a fact that the more indents you have in your code, the more complex the logic becomes. Take a look at the following example:

async function main() {
  const user = await getUser(id);

  if (user) {
    if (user.lastSeen) {
      const userSeen = dayjs(user.lastSeen);
    } else {
      const userSeen = dayjs();
      if (userSeen.isAfter(dayjs().subtract(1, "day"))) {
        showUserOnline();
      } else {
        showUserOffline();
      }
    }
  }
}

There isn't a specific rule for using if…else, but consider that the more if…else statements you have nested, the more complex the logic becomes. If you can, limit deeply nested if…else statements. Use switch…case in more complex cases, and flatten the logic tree as much as possible.

Limit Side-Effects

It can be said that Side-Effects have completely changed the way I write code since I learned about them. To discuss this issue, I have a detailed article on Pure Functions in JavaScript. Why should we know as early as possible?.

In general, limiting Side-Effects helps us have a more coherent program structure and avoids calling a function that changes the entire program's state.

Apply Functional Programming

Wherever you handle logic, break it down into smaller functions and give them names. Consider the following example:

const userRoleMap = {
  0: 'admin',
  1: 'moderator',
  2: 'user',
};

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then((user) => {
    return user.filter(user => user.active)
  })
  .then((user) => {
    return user.map(user => {
      return {
        id: user.id,
        name: user.name,
        roleName: userRoleMap[user.role],
      }
    })
  });

The code above fetches a list of users from an endpoint, filters out active users, and then adds the roleName property based on the role of each user. It may take some time to understand the meaning of the code because you have to focus on the logic. Instead, you can rewrite the code by separating the logic into smaller functions:

const userRoleMap = {
  0: 'admin',
  1: 'moderator',
  2: 'user',
};

const filterActiveUsers = (users) => {
  return users.filter(user => user.active)
};

const mapUsersRole = (users) => {
  return users.map(user => {
    return {
      id: user.id,
      name: user.name,
      role: userRoleMap[user.role],
    }
  })
};

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(filterActiveUsers)
  .then(mapUsersRole);

Look at the main part of the program; the entire logic is clearly exposed in filterActiveUsers and mapUsersRole. This allows us to quickly grasp the data processing flow. In the future, if you need to make changes, you can easily refer to the relevant functions.

Use Comments Wisely

Comments are a contentious issue; some say that those who comment excessively lack experience because they don't know how to write code that's easy to read. My perspective is to use comments when necessary and not rely too heavily on them to explain your code in detail.

Combine various elements such as naming and functional functions to indirectly explain how your code works. Unless you encounter overly complex logic or need to briefly describe the data flow, leave comments out. Important changes related to external documentation…

For example:

# 02/09/2023: Change the logic according to document DOC-2945
function getRandomUser() {
...

Additionally, there are many other cases where you can cleverly use comments, such as when using a feature of an external library.

# Limits Environment variables
# https://developers.cloudflare.com/workers/platform/limits/#environment-variables
function setEnv() {
...

In the example above, I'm using an environmental variable feature of Cloudflare and need to adhere to certain rules regarding limits. Attaching documentation helps colleagues easily access the documentation and understand how I wrote the code.

Document the Code You Write

Of course, a complex program can't rely solely on reading code to understand it completely. In addition, we need documentation describing most of the program's flow. It provides newcomers with study material and helps you improve your systematization skills.

Hone your skills in writing and conveying what you do. This is also one of the essential skills to help you advance in your career.

Finally, Keep Learning

Learn, learn more, keep learning… Learning is never enough, and it's never too much. What I mentioned here is just a personal perspective. In addition, I know there's still a lot more to learn from others. You can learn from colleagues or through open-source projects.

Conclusion

Above are some rules that I still apply in my daily work. Although I can't evaluate how effective they are, at least after a few weeks or months of reviewing the code I've written, I can still understand it :D. How about you? Are you applying any other methods to make your code more readable? Feel free to leave a comment!

Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (1)

Avatar
Trịnh Cường1 year ago
hay lắm bạn. nhưng mà nếu cứ chia nhỏ logic ra thì code phình rất to và cồng kềnh, tuy dễ đọc hơn thật nhưng mà lúc view sẽ bị phân tán các function, gây hơi mất tập trung khi đọc code, vì cứ phải vào hàm chia nhỏ xem, xong lại quay về hàm chính xem có gì, cứ thế cứ thế
Reply
Avatar
Xuân Hoài Tống1 year ago
Bạn Cường có thắc mắc mà trước kia mình cũng từng bị, việc chia nhỏ các hàm và tổ chức sao cho hợp lý thì lại phụ thuộc nhiều vào cách tổ chức mã của bạn. Ví dụ mình thường viết các hàm functional trong một tệp riêng biệt bên cạnh các tệp xử lý logic chính. Nếu đặt tên cho hàm đủ tốt, bạn sẽ biết chính xác vị trí hàm cần sửa ở đâu mà không cần phải xem xét từng functional một. Việc các hàm không có Side-Effect, tập trung vào làm nhiệm vụ đúng như tên của nó cũng góp phần giúp mã của bạn dễ đọc hơn.