Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Language Basics

Vars, def and let: Naming Values in Clojure

Learn how Clojure names values: global vars with def and defonce, local bindings with let, scope and shadowing, private vars, declare, and why names are not variables you reassign.

In many languages a "variable" is a box whose contents change. In Clojure you mostly bind a name to a value and leave it alone. There are two main tools: def, which creates a global named value inside a namespace, and let, which creates names that exist only inside one expression. Understanding the difference makes Clojure programs easier to read.

Global names with def

def creates a var in the current namespace and gives it a value:

CLOJURE
(def pi 3.14159)
(def app-name "Tutorial Shop")
(def max-items 50)

(* pi 2)            ; 6.28318

A var is a named box that lives in a namespace. def returns the var itself (printed as #'user/pi), so you may see that echoed in the REPL. Everything you define with def, including functions made with defn, is a var. Functions are just values stored in vars: (defn square [x] (* x x)) is the same as (def square (fn [x] (* x x))).

If you def the same name again, the var is rebound to the new value. That is useful in the REPL, where you keep refining definitions. In program code, use defonce for things that must be initialised once, such as a connection or a counter that should survive reloading a file:

CLOJURE
(defonce counter (atom 0))   ; evaluated again? the first value stays

Docstrings and metadata

def accepts an optional docstring, and metadata can mark a var private:

CLOJURE
(def ^{:doc "Maximum retry count."} max-retries 3)
(def ^:private secret-seed 42)       ; usable only inside this namespace

(defn- helper [x] (inc x))           ; defn- is a private function

^:private is shorthand for ^{:private true}. Private vars cannot be referred to from other namespaces. Use them to hide implementation details.

Referring to things before they are defined

Clojure reads a file top to bottom, so a name must be defined before it is used. If two functions call each other, forward-declare one:

CLOJURE
(declare is-odd?)

(defn is-even? [n] (if (zero? n) true (is-odd? (dec n))))
(defn is-odd?  [n] (if (zero? n) false (is-even? (dec n))))

Most of the time you can simply reorder your functions so that helpers come first.

Local names with let

let binds names for the duration of its body. The bindings are in a vector of name and value pairs:

CLOJURE
(let [width  10
      height 4
      area   (* width height)]
  (str "Area: " area))        ; "Area: 40"

Rules to remember:

  • Bindings are evaluated in order, so a later binding can use an earlier one (area uses width and height).
  • The value of the let form is the value of its last body expression.
  • The names exist only inside the let; outside it, they are gone.
  • Names are bound to values and are not reassignable. To "change" something, bind a new name or call a function that returns a new value.
CLOJURE
(let [price 100
      tax   (* price 0.2)
      total (+ price tax)]
  {:price price :tax tax :total total})
;; => {:price 100, :tax 20.0, :total 120.0}
JS Stand-in: let evaluates bindings in order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Scope and shadowing

Inner let forms can reuse a name, which hides the outer one only inside the inner form:

CLOJURE
(let [x 1]
  (let [x (+ x 10)]
    (println "inner:" x))     ; inner: 11
  (println "outer:" x))       ; outer: 1

This is shadowing, not mutation: the outer x is untouched. Use it sparingly. Distinct names are usually clearer.

You can also use _ as a name for values you do not need:

CLOJURE
(let [_ (println "side effect first")
      x 42]
  x)

A let is also the right place to give a name to a repeated calculation, which makes code both faster and clearer:

CLOJURE
(let [n (count items)]
  (if (zero? n) 0 (/ (reduce + items) n)))

Destructuring in let

The binding position can contain a pattern that pulls apart a vector or map:

CLOJURE
(let [[a b] [10 20]
      {:keys [name age]} {:name "Ada" :age 36}]
  (str name " (" age ") " (+ a b)))   ; "Ada (36) 30"

Destructuring is explained in depth in Destructuring; it works in let, function parameters and loops.

Dynamic vars (a short preview)

A var can be marked ^:dynamic so that binding can temporarily give it another value for the current thread. By convention such vars are named with earmuffs:

CLOJURE
(def ^:dynamic *indent* 0)

(defn show [s] (println (str (apply str (repeat *indent* " ")) s)))

(show "top")                       ; top
(binding [*indent* 4] (show "x"))  ;     x

Dynamic vars are used by the core library (*out*, *print-length*, *ns*), but they should be rare in your own code because they hide inputs: a function's result no longer depends only on its arguments.

JS Stand-in: a temporarily rebound 'dynamic' setting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Naming conventions

  • Use lowercase words separated by hyphens: max-items, parse-header.
  • Use ? for predicates (valid?), ! for side effects (reset!), -> in conversions (map->user).
  • Constants are written in plain lowercase too; Clojure does not use uppercase constant names.
  • Use *earmuffs* only for dynamic vars.

Choosing how to name a value

def Global var in a namespace.
let Local names inside one form.
^:private Hide a var from other namespaces.
^:dynamic Rebind per thread with binding.

Prefer let and function arguments over dynamic vars.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does def create?

    def interns a var in the current namespace and binds it to a value.
  2. 2. What is the value of (let [a 2 b (* a 5)] (+ a b))?

    b is 10 because let bindings are evaluated in order; then (+ 2 10) is 12.
  3. 3. What happens to the outer binding when an inner let reuses its name?

    That is shadowing: the outer name keeps its value outside the inner form.
  4. 4. How do you make a function usable only inside its namespace?

    defn- defines a private function (equivalent to ^:private on a defn).

Summary

  • def creates a global var in the current namespace; defonce keeps the first value; declare allows forward references.
  • let creates local, immutable names with sequential bindings and returns its last body expression.
  • Shadowing hides a name inside an inner form without changing the outer one.
  • ^:private and defn- hide implementation details; ^:dynamic with binding is for rare cases.
  • Choose hyphenated names with ? and ! conventions.

Next: Loops with loop, recur and doseq