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!
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!
For further actions, you may consider blocking this person and/or reporting abuse
11 -
Dorian Sabitov -
Dorian Sabitov -
11 -
Top comments (3)
Unless my understanding is incorrect (very possible) a Boolean in JavaScript is a primitive value of either
true
orfalse
, while there are other values that evaluate totrue
orfalse
when using a comparison operations. Primitive values are like the “building block” values - a string, a number, a Boolean, null, undefined, symbols, and bigints.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
Or in ruby
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.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 with11
. Similarly, certain values will resolve as true or false under the hood, so that when JS wants a Boolean value (true
orfalse
), but sees something else, it needs to convert it. If the input converts totrue
, the value is considered truthy, and if it converts tofalse
, 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:
FUN: