Last Updated: February 25, 2016
· kopasetik

Destructuring in both Javascript & Clojure (pt 1) - Intro

In EcmaScript 2015, <em>destructuring is a way to get exactly what you need from an object or an array and no more, no less.</em>

Let's start by looking at how you would destructure an object.

// For objects
let {bar: a, quux: b} = {foo: 'carrot', bar: 99, baz: 250, quux: 'feather'}

console.log(a) //=> 99
console.log(b) //=> feather

How is this useful? Among other things, you can use only what you need from the output of one function to more readily be the input of another function.

And here's how you would destructure an array:

// For arrays
let [batmanPunchSound, batmanPunchStrengh] = ['boom!', 9001, 'wham!', 'zap!']

console.log(batmanPunchSound) //=> boom!
console.log(batmanPunchStrengh)  //=> 9001

Clojure has had destructuring available from the get-go. If you swap out objects for hashmaps and arrays for vectors, the syntax looks a bit different (e.g. (let [{a :x b :z} {:x "yippee" :y "kai" :z "yay"}])), but the mechanism is the same. Here's how it works for (hash)maps:

; For maps
(def first-hashmap {:foo "carrot" :bar 99 :baz 250 :quux "feather"})

(let [{a :bar b :quux} first-hashmap]
  (println a)
  (println b))
;=> 99
;=> feather

For vectors, the process is similar to what we did for Javascript arrays:

; For vectors
(def first-vector ["boom!" 9001 "wham!" "zap!" ])

(let [[batmanPunchSound batmanPunchStrength] first-vector]
     (println batmanPunchSound)
     (println batmanPunchStrength))

;=> boom!
;=> 9001

For my next article, I'll show you to use destructuring in function parameters (with a tasty example). Stay tuned!