If Else in Clojure

Branching with if and else in Clojure is straightforward.

(ns if-else-example
  (:require [clojure.core :refer :all]))

(defn main []
  ;; Here's a basic example.
  (if (zero? (mod 7 2))
    (println "7 is even")
    (println "7 is odd"))

  ;; You can have an `if` statement without an else.
  (when (zero? (mod 8 4))
    (println "8 is divisible by 4"))

  ;; Logical operators like `and` and `or` are often useful in conditions.
  (when (or (zero? (mod 8 2)) (zero? (mod 7 2)))
    (println "either 8 or 7 are even"))

  ;; In Clojure, you can use `let` to bind variables before a condition.
  ;; These variables are available in all branches.
  (let [num 9]
    (cond
      (neg? num) (println num "is negative")
      (< num 10) (println num "has 1 digit")
      :else (println num "has multiple digits"))))

(main)

Note that in Clojure, you don’t need parentheses around conditions, and the syntax is quite different from imperative languages. Clojure uses prefix notation and has a more functional style.

To run the program:

$ clj if_else.clj
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Clojure doesn’t have a ternary operator, but the if expression can be used for similar purposes, often in a more concise way than in imperative languages.