CodeNewbie Community

loading...

What's the difference between boolean values and truthy and falsy values?

Leon
Flames, food, and code.
・1 min read

Hi guys!

I'm new to coding but absolutely loving the journey so far!

I recently came across the concept of truthy and falsy values. Can anyone explain these and how they differ from booleans?

Thanks much!

Discussion (3)

Collapse
anmpog profile image
Anthony Pogliano

Unless my understanding is incorrect (very possible) a Boolean in JavaScript is a primitive value of either true or false, while there are other values that evaluate to true or false when using a comparison operations. Primitive values are like the “building block” values - a string, a number, a Boolean, null, undefined, symbols, and bigints.

Collapse
djuber profile image
Daniel Uber

a value is said to be "truthy" when it follows the true side of an if block.
A "falsey" value follows the false/else side (or at least doesn't follow the true side if you don't have an else).

Every language has its own decisions about which those are (in some languages, only true and false are truthy or falsey, and using any other value as the test in an if statement is an error).

An example of truthiness in action would be this python snippet

if(5):
  print(5)
Enter fullscreen mode Exit fullscreen mode

Or in ruby

if 5
  5
end
Enter fullscreen mode Exit fullscreen mode

Both of these will show 5, even though neither value was "true".

For javascript, a good reference is MDN, but you'll definitely want to check each languages documentation for truth when you start using them.

Other languages might have different ideas about what's valid for if conditionals. Some treat 0 as falsy, some treat an empty array as falsy, some consider an empty string as falsy, some treat a pointer to nothing as falsy. Some only treat false as falsy, and everything else as truthy.

Collapse
denmch profile image
Den McHenry • Edited

Under the hood, JS will resort to conversion tables to try to resolve data types and keep humming. This can be tricky and make for lots humorous outcomes, like when you accidentally "add" a string to an integer and end up concatenating two strings so that "1" + 1 becomes "1" + "1" and you end up with 11. Similarly, certain values will resolve as true or false under the hood, so that when JS wants a Boolean value (true or false), but sees something else, it needs to convert it. If the input converts to true, the value is considered truthy, and if it converts to false, it's considered falsy.

I came up with a mnemonic a few years ago to remember the falsy values. Anything else is truthy. The mnemonic is "Falsy Values are N0 FUN!"

falsy values == N0 FUN

N0:

  • NaN
  • 0 or -0 or "" (empty string, i.e., String.length === 0)

FUN:

  • false
  • undefined
  • null