Fun With JavaScript Destructuring Assignment

JavaScript 5 5 Comments

By now you’ve probably heard that JavaScript is getting destructuring assignment in ECMAScript 6. It does just what it sounds like it does — it helps you extract values from structured data (such as arrays and objects). You can play with this right now. Just pop open Firefox, pull up the web console, and tinker (as of writing, these features are not yet supported in Chrome).

The most basic example:

You can return multiple values from a function:

There are several other interesting examples on the New in JavaScript 1.7 MDN page. For example, the variable swap:

And slightly more interesting rotation. Let’s make some candy-cane stripes:

But I wrote this post to tell you about my favorite thing about destructuring assignment. You can use it to tame function parameters:

Note that we were able to deep dive into the object passed into logSongInfo and even specify the name. You don’t have to deep dive into an object to specify a new variable name:

Those are some neat parlor tricks, but what’s the real practical value? Well, for one thing, it makes it easier to reason about objects. For example, say you have a group of babies, and you want to find all of George’s kids:



Notice how the semantics are altered. In the first example, you specify the baby object as the formal parameter. In the destructuring example, the function signature tells you exactly what you’re interested in. I find this much more readable, personally.

I’m excited for this new addition to the JavaScript specification. If you don’t want to wait, destructuring assignment is one of several great features that already exist in CoffeScript. I encourage you to try it out. It’s a bit like getting to explore the future of JavaScript today.

  1. Joshua Tenner - October 7, 2013


    I think I would have a field day with this.

Add Comment Register

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">