Clojure Conditionals — if, when, cond & Truthiness | Episode 5
0views
C
CelesteAI
Description
In most languages, if is a statement. In Clojure, it's an expression that returns a value. This changes everything about how you think about branching.
In this episode we explore if, when, and cond — three ways to branch in Clojure. We also uncover a surprise: zero and empty strings are truthy. Only nil and false are falsy. By the end you'll write a conditionals.clj file that demonstrates each pattern plus a cond-based classifier function.
Student code: https://github.com/GoCelesteAI/clojure-for-beginners/tree/main/episode05
Every keystroke is shown on screen with generous pauses so you can follow along at your own pace.
What You'll Learn:
- if as an expression that returns a value (not a statement)
- Both branches are required in if — then and else
- when for single-branch conditionals (returns nil when false)
- Truthiness — only nil and false are falsy; 0, empty string, empty list are all truthy
- cond for multi-way branching with condition/result pairs
- :else as the default catch-all in cond
- Writing a classifier function with cond
- Running conditionals.clj with :!clj -M %
Key REPL Demo:
(if true "yes" "no") returns "yes"
(if false "yes" "no") returns "no"
(if nil "yes" "no") returns "no" (nil is falsy)
(if 0 "yes" "no") returns "yes" (0 is truthy!)
(if "" "yes" "no") returns "yes" (empty string truthy!)
(when true "hello") returns "hello"
(when false "hello") returns nil
Timestamps:
0:00 - Intro
0:12 - Preview: branching as expressions
0:32 - Start the REPL (no rlwrap flicker)
0:39 - if basics — true and false
0:53 - Truthiness — nil, 0, empty string
1:12 - when — single branch
1:25 - cond — multi-way branching
1:37 - Exit REPL with Ctrl+D
1:42 - Write conditionals.clj in Neovim
1:54 - if section — bind x, test with if
2:26 - when section
2:50 - Truthiness section — 0, "", nil
3:33 - cond section — describe function
4:39 - Run with :!clj -M %
4:43 - Output explained line by line
5:39 - Review the file
5:49 - Recap
6:17 - What's next — Episode 6
Key Takeaways:
1. if is an expression — it returns a value, not just controls flow. Both branches are required.
2. when handles the single-branch case — returns nil when false.
3. Only nil and false are falsy. Everything else (including 0 and "") is truthy.
4. cond gives you multi-way branching with test/result pairs and :else as the catch-all.
Series Roadmap:
- Episodes 1-6: REPL & first values
- Episodes 7-13: Collections & sequences
- Episodes 14-19: Functional core
- Episodes 20-24: Namespaces, projects, testing
- Episodes 25-30: State & concurrency
- Episodes 31-35: Data modeling
- Episodes 36-38: Macros
- Episodes 39-41: Interop, Babashka, uberjars
- Episodes 42-45: Capstone — web app deployment
Next up — Episode 6: Your First Script (deps.edn).
Taught by CelesteAI. Like & subscribe for more Clojure tutorials!