Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Language Basics

Booleans, nil and Conditionals in Clojure

Master Clojure truthiness (only nil and false are falsey), the conditional forms if, when, cond, case, condp, if-let and when-let, the logic operators and nil-safe idioms.

Decisions in Clojure are made with expressions that return values. There is no separate "statement" if; an if evaluates to one of its branches, so you can use it anywhere a value is expected. This lesson covers truthiness, the family of conditional forms, the boolean operators and the handling of nil.

Truthiness: only two falsey values

Clojure has exactly two falsey values: false and nil. Everything else is truthy, including 0, the empty string "", the empty vector [] and the empty map {}.

CLOJURE
(if 0 "truthy" "falsey")      ; "truthy"
(if "" "truthy" "falsey")     ; "truthy"
(if [] "truthy" "falsey")     ; "truthy"
(if nil "truthy" "falsey")    ; "falsey"
(if false "truthy" "falsey")  ; "falsey"

This differs from JavaScript and Python, where 0 and "" count as false. To test for an empty collection, use empty?, or use the seq idiom: (seq coll) returns nil for an empty collection and the sequence otherwise.

JS Stand-in: Clojure truthiness in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The comparison shows exactly where the two languages disagree: 0, "" and (in JavaScript too) [], {}. Watch for this if you port code.

if and when

if takes a test, a "then" expression and an optional "else". Without an else, the result is nil when the test fails:

CLOJURE
(if (> 5 3) "yes" "no")      ; "yes"
(if (> 1 3) "yes")           ; nil

Each branch is a single expression. To run several expressions in a branch, wrap them in do:

CLOJURE
(if (> n 0)
  (do (println "positive")
      :ok)
  :not-ok)

When there is no else branch and you want several expressions, use when, which has an implicit do. Its counterpart is when-not:

CLOJURE
(when (> n 0)
  (println "positive")
  :ok)                       ; nil if n is not positive

(when-not (empty? items)
  (process items))

As a rule of thumb: use if when both outcomes matter and when when you only act in the true case.

cond: many branches

cond tests pairs of "condition, result" in order and returns the result for the first truthy condition. The keyword :else (which is truthy) acts as the default:

CLOJURE
(defn grade [score]
  (cond
    (>= score 90) "A"
    (>= score 80) "B"
    (>= score 70) "C"
    :else         "F"))

(grade 85)   ; "B"

If no condition matches and there is no :else, cond returns nil. Writing :else is a convention; any truthy constant would do.

case: constant dispatch

case compares a value against literal constants and jumps straight to the match, much like switch. The constants are not evaluated, and they can be grouped in a list:

CLOJURE
(defn day-type [d]
  (case d
    (:sat :sun) "weekend"
    (:mon :tue :wed :thu :fri) "weekday"
    "unknown"))            ; the last single expression is the default

(day-type :sat)   ; "weekend"
(day-type :xyz)   ; "unknown"

Without a default, case throws IllegalArgumentException when nothing matches. Use cond or condp when your tests are not simple constants. condp applies a predicate to each test value and the expression:

CLOJURE
(condp = 3
  1 "one"
  2 "two"
  3 "three"
  "other")    ; "three"

if-let and when-let

A very common pattern is "if this value exists, use it". if-let binds a name only when the test is truthy, and the binding is visible only in the then branch:

CLOJURE
(def users {1 "Ada" 2 "Grace"})

(if-let [name (get users 2)]
  (str "Found " name)
  "No such user")         ; "Found Grace"

(when-let [name (get users 9)]
  (println "Hello" name)) ; nothing happens, returns nil

if-some and when-some are the same but treat only nil as failure, so a stored false counts as a real value.

and, or, not

The logic operators are macros that short-circuit and return one of their arguments, not necessarily true or false:

CLOJURE
(and 1 2 3)         ; 3       the last value if all are truthy
(and 1 nil 3)       ; nil     the first falsey value
(or nil false 7)    ; 7       the first truthy value
(or nil false)      ; false   the last value if none are truthy
(not 0)             ; false
(not nil)           ; true

That makes or ideal for defaults: (or (:port config) 8080). Be careful with false values, because (or false 8080) would also give 8080 even if false was intentional.

JS Stand-in: and / or return values, not booleans

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Predicates

Functions that return a boolean end in ? by convention:

CLOJURE
(nil? nil)        ; true
(some? 0)         ; true     (anything except nil)
(true? true)      ; true     (only the value true)
(string? "x")  (number? 1)  (keyword? :a)  (map? {})  (vector? [])
(empty? [])       ; true
(every? even? [2 4 6])   ; true
(some even? [1 3 4])     ; true

Note that some returns the first truthy result of the predicate, not true, and (some even? [1 3 5]) returns nil.

Working safely with nil

nil represents "nothing" and is what you get from missing map keys, empty seq, or when with a failed test. Many core functions are nil-friendly: (count nil) is 0, (first nil) is nil, (conj nil 1) is (1) and (str nil) is "". Calling a function on nil, however, throws a NullPointerException, as in (.length nil). The nil-safe navigation helpers are some-> and some->>, which stop at the first nil:

CLOJURE
(some-> {:user {:name "Ada"}} :user :name str/upper-case)  ; "ADA"
(some-> {:user nil} :user :name str/upper-case)             ; nil

You will see them again in Composition and Threading Macros.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which value is falsey in Clojure?

    Only nil and false are falsey; everything else, including 0 and empty collections, is truthy.
  2. 2. What does (or nil false 7 9) return?

    or returns the first truthy argument, which is 7.
  3. 3. What does case do when no constant matches and there is no default?

    case throws IllegalArgumentException when nothing matches and no default is given.
  4. 4. When is when better than if?

    when has an implicit do and no else branch, so it suits side effects in the true case.
  5. 5. What does (if-let [x (get {:a 1} :b)] x "missing") return?

    get returns nil for the missing key, so the else branch runs.

Summary

  • Only nil and false are falsey; 0, "" and [] are truthy.
  • if returns a value; when is for the true case only; cond handles multiple tests; case dispatches on literal constants; condp applies a predicate.
  • if-let and when-let bind a value only when it is truthy; the -some versions only reject nil.
  • and and or short-circuit and return one of their arguments, which makes or handy for defaults.
  • Use some?, nil?, empty? and seq for checks, and some-> to navigate safely through possible nils.

Next: Vars, def and let