How Understanding Falsy Values Can Improve Your Javascript Code Readability

sharmakushal

Kushal sharma

Posted on September 24, 2023

How Understanding Falsy Values Can Improve Your Javascript Code Readability

In JavaScript, falsy values are values that are considered "false" when encountered in a boolean context.

Understanding the use of falsy values can help you reduce boolean checks in your code. The number 0 (including -0), null, undefined, false, NaN, and an empty string ("") are considered falsy values in JavaScript.

This is the only theory that needs to be known. Now, let's explore how to apply this concept in real-life examples. I will provide some real-life examples.

Suppose we have an array of users:

const users = [
  {
    name: "Kushal",
    marks: 99
  },
  { name: "" },
  {
    name: "John"
  },
  { name: null, marks: 87 },
  { marks: 34 },
  {
    name: "Bob",
    marks: 0
  }
];
Enter fullscreen mode Exit fullscreen mode

Requirement 1

Print users whose name has at least 1 character.

The normal way to achieve this is:

for (let i = 0; i < users.length; i++) {
  if (
    users[i].name !== undefined &&
    users[i].name !== null &&
    users[i].name !== ""
  ) {
    console.log("User name is", users[i].name);
  }
}

Enter fullscreen mode Exit fullscreen mode

However, using falsy values, you can simplify the code like this:

for (let i = 0; i < users.length; i++) {
  if (users[i].name) {
    console.log("User name is", users[i].name);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this case, if the name comes from any of the falsy values like undefined, null, an empty string, or others, it will be considered false in the if block.

Requirement 2

Print the user name if it exists; otherwise, print "N/A".

The normal way to achieve this is:

for (let i = 0; i < users.length; i++) {
  if (
    users[i].name !== undefined &&
    users[i].name !== null &&
    users[i].name !== ""
  ) {
    console.log("User name is", users[i].name);
  } else {
    console.log("User name is N/A");
  }
}
Enter fullscreen mode Exit fullscreen mode

Using falsy values, you can simplify the code like this:

for (let i = 0; i < users.length; i++) {
  console.log("User name is", users[i].name || "N/A");
}
Enter fullscreen mode Exit fullscreen mode

Hope you like the article, if you please consider to like and comment.

And you are on Twitter can you follow me there as well, I keep posted these kinds of stuff there as well => Follow @kushal_js

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
sharmakushal
Kushal sharma

Posted on September 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About