if

special formsince v0.0-927 clojure.core/ifEdit
(if test then else?)

Details:

If test is not false or nil, then is evaluated and returned. Otherwise, else? is evaluated and returned. else? defaults to nil if not provided.

if is one of ClojureScript's special forms and is a fundamental building block of the language. All other conditionals in ClojureScript are based on ifs notion of truthiness (ie: anything other than false or nil).


Examples:

(def v [1 2])

(if (empty? v) "empty!" "filled!")
;;=> "filled!"

(str "This vector is "
  (if (empty? v) "empty!" "filled!"))
;;=> "This vector is filled!"

See Also:


Source docstring:
Evaluates test. If not the singular values nil or false,
evaluates and yields then, otherwise, evaluates and yields else. If
else is not supplied it defaults to nil.
Parser code @ clojurescript:src/main/clojure/cljs/analyzer.cljc
(defmethod parse 'if
  [op env [_ test then else :as form] name _]
  (when (< (count form) 3)
    (throw (compile-syntax-error env "Too few arguments to if" 'if)))
  (when (> (count form) 4)
    (throw (compile-syntax-error env "Too many arguments to if" 'if)))
  (let [test-expr (disallowing-recur (analyze (assoc env :context :expr) test))
        then-expr (allowing-redef (analyze (set-test-induced-tags env test) then))
        else-expr (allowing-redef (analyze env else))]
    {:env env :op :if :form form
     :test test-expr :then then-expr :else else-expr
     :unchecked *unchecked-if*
     :children [:test :then :else]}))

Emitting code @ clojurescript:src/main/clojure/cljs/compiler.cljc
(defmethod emit* :if
  [{:keys [test then else env unchecked]}]
  (let [context (:context env)
        checked (not (or unchecked (safe-test? env test)))]
    (cond
      (truthy-constant? test) (emitln then)
      (falsey-constant? test) (emitln else)
      :else
      (if (= :expr context)
        (emits "(" (when checked "cljs.core.truth_") "(" test ")?" then ":" else ")")
        (do
          (if checked
            (emitln "if(cljs.core.truth_(" test ")){")
            (emitln "if(" test "){"))
          (emitln then "} else {")
          (emitln else "}"))))))