DEV Community

Cover image for 🤯Understanding Truthy and Falsy in JavaScript
Yuli Petrilli
Yuli Petrilli

Posted on • Edited on

🤯Understanding Truthy and Falsy in JavaScript

In this article we will be looking at the definitions of two key expressions in Javascript: truthy and falsy.

The first time I bumped into this was while talking with a friend who was teaching me some definitions and tips in Javascript, and honestly, this one wasn't that fast to make sense in my mind at first try.

That's why I've decided to write about these important definitions in the most easy and straightforward way, so, let's begin!

Truthy Values

Truthy values are values that are considered true when evaluated in a boolean context. In JavaScript, the following values are truthy:

true
non-zero numbers
non-empty strings
objects
arrays
functions

For example, consider the following code:

let x = "hello";
if (x) {
console.log("x is truthy");
} else {
console.log("x is falsy");
}
Enter fullscreen mode Exit fullscreen mode

We can see that the value of x is a non-empty string, which is a truthy value. Therefore, the if block is executed, logging "x is truthy" to the console.

Falsy Values

Falsy values are values that are considered false when evaluated in a boolean context. In JavaScript, the following values are falsy:

false
0
-0
NaN
null
undefined
empty strings ("" or '')
document.all

For example, consider the following code:

let y = null;
if (y) {
console.log("y is truthy");
} else {
console.log("y is falsy");
}
Enter fullscreen mode Exit fullscreen mode

We can see that the value of y is null, which is a falsy value. Therefore, the else block is executed, logging "y is falsy" to the console.

Conclusion

Understanding truthy and falsy values is essential to writing reliable and bug-free code. By knowing which values are considered truthy and which are considered falsy, you can write more concise and readable code that handles edge cases and unexpected inputs.

Happy learning and thank you for reading!

If this article was helpful to you, don't forget to hit that ❤️ button and support me with a follow, i will keep posting more content about tech, programming, career development and more! :)

Until next time!

Top comments (0)