Search

October 5, 2020

Clojure Goodness: There Is Truth In Many Things

In Clojure there are only two things false in a boolean or conditional context: false and nil. All other values are threated as true. A value that is false in a boolean context is also called falsey, and a value that is true is called truthy.

In the following example we use false and nil as falsey and several other values as truthy values:

(ns mrhaki.core.truthy-falsey
  (:require [clojure.test :refer [is]]))

;; Only nil and false are falsey.
(is (= false (boolean false)))
(is (= false (boolean nil)))
(is (= false (boolean ({:cool "Clojure"} :language))))

(is (= :falsey (if nil :truthy :falsey)))

;; Other values are truthy.
(is (= true (boolean true)))
(is (= true (boolean "mrhaki")))
(is (= true (boolean 0)))
(is (= true (boolean 1)))
(is (= true (boolean '())))
(is (= true (boolean [1 2 3])))
(is (= true (boolean {})))
(is (= true (boolean ({:rocks "Clojure"} :rocks))))

(is (= :truthy (if "Clojure" :truthy :falsey)))
(is (= :truthy (if "" :truthy :falsey)))
(is (= :empty-but-truthy (if [] :empty-but-truthy :empty-and-falsey)))

Written with Clojure 1.10.1.