liveBook · Manning

Conditional logic

As explained in Clojure: The Essential Reference

Conditional branching is a control-flow technique that selects which expressions to evaluate according to a condition.

Conditional logic selects which expressions to evaluate according to a condition. In Clojure, branching constructs are part of the language’s small, composable foundation, and every conditional form returns a value. Because unselected branches are not evaluated, conditionals can control effects as well as choose results. section 3.0 section 3.3

Choose the form that matches the shape of the decision:

  • `if` and `if-not` select between two branches. Their required test expression determines whether the then or else expression runs; omitting else returns nil when that branch would run. section 3.3.1
  • `when` and `when-not` conditionally run one or more expressions. They implicitly wrap those expressions in `do` and return nil when the condition does not match. section 3.3.1
  • Tests accept any Clojure expression interpreted by logical truth: only `false` and `nil` are false; values such as `0`, an empty string, and an empty list are true. section 3.2
  • Use the `-not` forms when the negative condition deserves direct emphasis rather than an inverted positive expression. section 3.3.1

Two-way choice and guarded work

A coin toss chooses one result without evaluating both branches: (defn toss [] (if (> 0.5 (rand)) "head" "tail")) (take 5 (repeatedly toss)) ;; ("head" "head" "head" "head" "tail") For one-sided work, `when` avoids an explicit else branch: (when s (try (.close s) (catch Exception e (println "error closing socket"))) ;; nil section 3.3.1 section 3.3.1

Table 3.1. Common Clojure values and their boolean translation

Description

Example

Boolean Value

Number zero

0

true

Empty string

""

true

Empty list

()

true

List of nil

(nil)

true

Nil

nil

false

Use the truth-value table to check edge cases before placing values in conditional tests. section 3.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines four core forms, their inputs, outputs, arities, truth rules, and lazy branch evaluation.
Examples
Demonstrates coin tossing, recursive tree-depth calculation, and guarded socket cleanup.
What it assumes
Assumes valid Clojure expressions and teaches logical truth from Clojure's treatment of values.
What you can do after
Apply it via Clojure's `if`, `if-not`, `when`, and `when-not` to select expressions and guard operations.
How it connects
Connects conditional logic with boolean operators, recursion, functional programming, and side-effect management.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.