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
}
];
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);
}
}
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);
}
}
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");
}
}
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");
}
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
Top comments (0)