liveBook · Manning

Logical AND operator

As explained in Clojure: The Essential Reference

Logical conjunction is an operation that is true only when all of its operands are true.

Clojure's `and` combines conditions while preserving short-circuit evaluation. It evaluates expressions from left to right and stops at the first `false` or `nil`; otherwise, it returns the final expression's value rather than necessarily returning a Boolean. section 3.2.2

`and` accepts zero or more expressions:

  • With no arguments, it returns `true`. section 3.2.2
  • With one argument, it returns that argument. section 3.2.2
  • It returns `false` when an expression produces `false`, and `nil` when an expression produces `nil`. section 3.2.2
  • If every expression is logically true, it returns the last expression's value. section 3.2.2

Guarding a conditional

Use `and` to require several conditions before performing an action: (let [probe {:temp 150 :rpm "max"}] (when (and (> (:temp probe) 120) (= (:rpm probe) "max")) (println "Too hot, going protection mode."))) ;; Too hot, going protection mode. The second test is skipped when the temperature test is false. This makes `and` useful for guarding operations that should run only after earlier checks succeed. section 3.2.2

Guarding nil-sensitive work

Because only `false` and `nil` are falsey in Clojure, `and` can protect later expressions from a missing value: (defn path [s] (let [s (and s (.trim s))] (and (seq s) (subs s 0 (.lastIndexOf s "/"))))) (path "/tmp/exp/lol.txt") ;; "/tmp/exp" (path "") ;; nil (path nil) ;; nil section 3.2

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 truthiness table to check how numbers, empty collections, empty strings, and `nil` behave inside `and` conditions. section 3.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines arity, return values, truthiness, and short-circuit behavior, with examples; stops short of broader comparison operators.
Examples
Uses a temperature probe, path extraction, truth tables, and macro expansion to demonstrate behavior and implementation.
What it assumes
Assumes basic Clojure expressions and introduces truthiness, falsey values, variadic arity, and macro-based short-circuiting.
What you can do after
Apply `and` to compose conditions, guard nil-sensitive operations, and exploit its returned values.
How it connects
Connects logical conjunction with short-circuit evaluation, truthiness, nil checking, macros, and logical disjunction.

Also explained in

Compare how 7 books explain logical AND operator →

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.