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

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

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » Read more

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!

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (1)

Leave a comment...
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.