In Clojure, any value can be considered as “truthy” or “falsey” for the purposes of a conditional expression.
The rule is very simple:
- nil and false – are “falsey”
- everything else – is considered “truthy”
This rule may seem strange if you come from a world with a strictly defined boolean type (like Java). But it turns out that it enables some neat tricks in Clojure code that are well worth knowing.
1. Acting on non-empty collections
Often you want to perform some actions on a sequence of items in a collection if and only if the collection is non-empty. The important thing to note is that (seq coll) returns nil if a collection is empty, so you can use it directly with if-let as follows:
(if-let [s (seq coll)] (do-something-with-sequence s) empty-result)
2. Providing default values
Often you want to provide a default value if one is not provided. Since non-presence is generally defined as nil, you can use the short-circuiting or macro to fill in a default value.
(or value default-value)
If a value is provided it will be used directly. If value is nil then the or operator will proceed to use the default value
3. Cond handling of :else
Since the keyword :else is truthy, it can be used as a catch-all at the end of a cond expression:
(cond (condition-1? args) "Result 1" (condition-2? args) "Result 2" :else "Default result")