DEV Community

Gustavo Nunes
Gustavo Nunes

Posted on

Truthy, true, Falsy, false... What on earth am I getting into?!

If you're studying programming or working with this vast and sometimes complicated area, you may or may not have come across the terms truthy or falsy. But what do they mean? Aren't they supposed to be the same as the boolean values true and false?

In a short and straight answer, truthy and falsy are concepts that aim to evaluate different types of data (strings, numbers, etc.) into boolean values. This evaluation will occur in your code's expressions and conditional operations (if, else if, etc.). The rules may work differently depending on which programming language you're using, but in general, they are:

Falsy:

  • Strings: Empty strings.
    • Ex: const empty = "";
  • Numbers: The value is zero.
    • Ex: const number = 0;
  • Null pointers: The assigned value is null or undefined.
    • Ex: const nullValue = null;
    • Ex: const undefinedValue = undefined;

Truthy:

  • Strings: Strings filled with any value.
    • Ex: const word = "Truthy";
  • Numbers: Any number different than zero.
    • Ex: const positive = 10;
    • Ex: const negative = -1;
  • Objects: Any object.
    • Ex: const noData = {};
    • Ex: const data = { word: "Word" }
  • Arrays: Any array.
    • Ex: const emptyArray = [];
    • Ex: const array = [1, 2, 3];

As for variables and constants, the rule works according to the type of the assigned value.

Keep in mind that I used Javascript in my truthy/falsy examples, so it may vary if you're using a different language. I do encourage you to go ahead and try out what does and does not work in your language!

Top comments (0)