Immutability
Now that you've had a basic introduction to ClojureScript's data structures, let's talk a bit about immutability. Almost all of ClojureScript's data types are immutable, which means that once they're defined, including them in an expression won't change their underlying value. This concept can take a bit of getting used to, so let's take a look at a few examples. As a point of contrast, we'll use JavaScript as an example of a language where data types are mutable.
Let's start with an example using a vector. First, we'll define a vector with one element in it, the integer 1
:
cljs.user=> (def x [1]) ;; => #'cljs.user/x
Now, we'll call conj
on x
. We've already talked a bit about how conj
works earlier in this chapter, but just to review, the conj
function returns a new vector that consists of the original vector with any of the following arguments added to the original vector:
cljs.user=> (conj x 2) ;...