DEV Community

Cover image for Truthy and Falsy values in JS
Tahir Ahmed Tapadhar
Tahir Ahmed Tapadhar

Posted on • Updated on

Truthy and Falsy values in JS

"Every value in JavaScript has an inherent boolean value. When that value is evaluated in the context of a boolean expression, the value will be transformed into that inherent boolean value."
The paragraph above is pretty dense with information. You should probably re-read it again.

Falsy values

A value is falsy if it converts to false when evaluated in a boolean context. For example, an empty String "" is falsy because, "" evaluates to false. You already know if...else statements, so let's use them to test the truthy-ness of "".
Alt Text

Hereโ€™s the list of all of the falsy values:

  1. Boolean value false
  2. number 0
  3. number negative -0
  4. BigInt 0n
  5. empty string ""
  6. null type
  7. undefined type
  8. NaN(stands for Not a Number).

There are eight falsy values in all of JavaScript! MDN
(at the time of writing this article)

Truthy values

A value is truthy if it converts to true when evaluated in a boolean context. For example, the number 1 is truthy because, 1 evaluates to true. Let's use an if...else statement again to test this out:
Alt Text

Here are some other examples of truthy values:

  • true
  • 42
  • "pizza"
  • "0"
  • "null"
  • "undefined"
  • {}
  • []

Simply put: if it's not in the list of falsy values, then it's truthy.

Be a little extra careful when working with the same element value but different element type. For example, 0 is a number while "0" is a string. Similarly null is different(falsy) from string "null"(truthy) and undefined(falsy) is different from string "undefined"(truthy)
Alt Text

Comparison operator

Even though as mentioned above that [] is a truthy value but behaves differently when used in conjunction with a comparison operator like ==, it evaluates to false. Likewise null is a falsy, but when used with a == operator evaluates to true. Similary for undefined and NaN.
Alt Text

That's all there is to this topic. For some people truthy & falsy values might be not of a big deal, but knowing how they behave can save you some real time instead of just scratching your head.Let me know if you guys have any questions. Happy Learning..

Top comments (0)