Over a million developers have joined DZone.

Clojure: Truthy and Falsey

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Truthy and Falsey are important concepts in Clojure. The best description I've seen is in The Joy of Clojure, go buy it.

Depending on your language background you may have very different ideas on what evaluates to true and what evaluates to false. In Clojure, the answer to this is very straightforward.
Both nil and false are treated as "false" and everything else is treated as true.
Let's hit the REPL.
user=> (if true "yes" "no")
"yes"
user=> (if false "yes" "no")
"no"
Okay, that much should be obvious. However, it's important to note that nil is also considered false, which is why we say:
In Clojure nil and false are considered "false" and therefore we say they are both "falsey".
Another quick trip to the REPL to verify that nil is falsey.
user=> (if nil "yes" "no")  
"no"
As expected, the else is evaluated.

There are other values that are considered false in other languages, this does not apply to clojure.
All non-falsey values are considered "truthy" and evaluate as such.
Here are some common examples of truthy values in Clojure that are falsey in other languages.
user=> (if -1 "still true" "false")
"still true"
user=> (if 0 "still true" "false") 
"still true"
user=> (if [] "still true" "false")
"still true"
user=> (if (list) "still true" "false")
"still true"
As it says in The Joy of Clojure: Every[thing] is "true" all the time, unless it is nil or false.

From http://blog.jayfields.com/2011/02/clojure-truthy-and-falsey.html

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}