DEV Community

Analogy | Absence | Example
Analogy | Absence | Example

Posted on

Understanding "truthiness" by comparing it to "falsiness"

What is truthiness?

If you write a statement where you are testing if something is true or not--like an if statement that uses a logical operator like ||, !, or &&--you expect that statement to return a boolean value of true or false. Sometimes it doesn't resolve to a boolean value--true or false--yet, nevertheless, it gets interpreted like a boolean value. We call those values "truthy" or "falsey".

In Javascript, we can list all the falsy values. They are:

  • null
  • undefined
  • NaN (Not a Number)
  • "" (empty string)
  • false
  • 0

There is not a corresponding list of "truthy" values, because all values are truthy unless they are defined as fasly or are one of the examples listed above.

We can, however, demonstrate "truthiness" by showing examples of if statements that resolve to truthy values. Let's start!


An empty string is falsy, but an empty array or empty object is truthy

This is because an empty string is nothingness, but an empty array is still a container and an empty object is still a container. The array and object can be filled with content at a later point.

if ("") {
  console.log("hello") // (nothing)
}

if ({}){
  console.log("hello") // hello
}
if ([]){
  console.log("hello") // hello
}
Enter fullscreen mode Exit fullscreen mode

0 is falsy, but "0" is truthy

This is because the value of 0 is zero, and therefore nothing, but "0" is a string with a single character that looks like a zero.

if (0){
  console.log("hello") // (nothing)
}

if ("0") {
  console.log("hello") // hello
}
Enter fullscreen mode Exit fullscreen mode

false is falsy, but true is truthy

I can't explain why this is, I just accept it.

if (false){
  console.log("hello") // (nothing)
}

if (true) {
  console.log("hello") // hello
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)