K. Sabbak

Code Princess

Truthy and Falsy

December 22, 2017

I always thought that the threshold for me to feel like a "real programmer" would be when I was able to use ternary statements confidently, and while that certainly helped, I feel like the real turning point for me was understanding truthy and falsy.

True and False are simple enough concepts. And in programming they tend to be classified as booleans and they tend to look like true or False. Statements like 1 == 1 evaluate to True (the boolean), and statements like 100 < 2 evaluate to False (the boolean). And in some languages, that's all there is to know.

But not all languages. Some languages have this more nebulous idea of "truthy" and "falsy". In these languages, one isn't limited to strictly booleans and statements that evaluate to booleans. In these languages, you can use . . . kind of whatever.

In languages that use truthy and falsy, you can put objects or types that aren't booleans in a place where you'd normally expect a boolean, like control flow statements.

For example, if you were to use the following bit of code in Swift, XCode would start crying.

if [] {
    print("Hello!")
}

That's because Swift is one of those languages that doesn't use truthy and falsy and it wants a bool or something that evaluates to a bool. (Bool is Swift's name for boolean.)

On the other hand, languages that do use truthy and falsy, like Ruby, are perfectly happy with the following:

if [] 
    puts "Hello!"
end

Everything works out fine in that example and "Hello!" will be printed to the console. But what happens if we look at Python, another language that accepts truthy and falsy:

if []: 
    print("Hello!")

Python evaluates the code just fine, but unlike in the Ruby example where an empty array is truthy, an empty list in Python is falsy, and "Hello!" will never print.

In languages that use truty and falsy, knowing the list of what evaluates to falsy (typically shorter than the list that evaluates to truthy), is very important since debugging can be very hard if you get it wrong. That being said, a good grasp of truthy and falsy in the language you're writing in can make your code a lot more expressive and readable. And that expressiveness and readability is exactly what made me feel like I was finally really programming for real.

Tags: booleans fundamentals