JavaScript Destructuring Assignment
On following the commentary around My TXJS Talk by Brendan Eich, I noticed a debate on Twitter between @brendaneich and several developers about one particular facet in the talk: destructuring. I wanted to take a look a this area and give some examples that illustrate why it might be useful to JavaScript developers in general.
Is destructuring an unnecessary language feature that just lets us swap values, or is there more to it?
What is Destructuring?
Many languages include pattern matching features that make pattern matching more expressive and concise. Pattern matching just means the ability to check a sequence of things for a given pattern; regular expressions are an obvious example. Functional languages include other pattern matching features, and one is called destructuring. Common Lisp includes a destructuring-bind macro, and there’s an example of this in On Lisp by Paul Graham in Destructuring on Lists.
In Clojure, let supports abstract structural binding:
(let [[a b] [1 2 3]]
(println "a:" a " b:" b))
This will print “a: 1 b: 2”. In Lisp it’s easy to see why destructuring is useful because the language is based around lists, and it has so many useful tools for dealing with them.
In JavaScript
As JavaScript 1.7 destructuring assignment is supported. That means you can use it in Mozilla’s interpreters and Firefox 2+. The canonical example is value swapping:
var a = 1, b = 2;
[a, b] = [b, a];
// a = 2, b = 1
That’s not particularly exciting unless you need to swap around lots of values, but what might be convenient for some APIs is the implications it has for return values:
function f() {
return [1, 2];
}
var a, b;
[a, b] = f();
That’s potentially useful, but also potentially confusing. Do we really need destructuring assignment? Well, let’s think about it in the context of Lisp again. What makes destructuring useful in Lisp-like languages is dealing with lisps. Similarly, in JavaScript the Object unlocks a great deal of power and flexibility.
Destructuring assignment in the context of Object gives rise to this:
var o = { name: 'Alex', permissions: 'Admin', email: 'alex@example.com' };
var {name, email} = o;
That sets a variable called name to 'Alex' and one called email to alex@example.com. Imagine combining this with iterations over JSON returned from an API, and it should be obvious where a lot of unnecessarily verbose code can be made more concise.
Further Reading
This is a basic Destructuring Assignment 101 lesson, but as I intimated in the last paragraph, destructuring assignment can be useful in a wider range of situations. To read more, specifically about JavaScript destructuring, have a look at these pages:
Related Topics in Other Languages
- Haskell: Irrefutable Patterns
- Points in the Pattern Matching Design Space
- Lisp Destructuring
- More Lisp Destructuring Examples
- Clojure’s Special Forms (includes destructuring examples)
- Run Time Pattern Matching
- Destructuring in Ruby