May 242006

While I slept, destructuring assignment got checked into JavaScript 1.7. I got it built and played with it for a while this morning. It’s going to be a nice addition to the language, I think. A few of the samples from the proposal document don’t work yet, because they rely on other features that haven’t landed yet.

Destructuring assignment is the ability to pull multiple return values from a function, like this:

function f() {
  return ["Jerry", 5, true];
var [a, b, c] = f();

After running this code, a is “Jerry”, b is 5, and c is true. You can also ignore results:

var [a, , c] = f();

This ignores the value 5 from the result.

So that’s pretty neat.

Some folks might wonder why I’ve not yet posted the doc onto MDC. There are two reasons. The main reason is that with my Internet access constantly going up and down, it behooves me to keep it on my local wiki so I can access it even when I’m not online. Having my own copy of MediaWiki running on my Mac at home has really helped productivity during my long bout with the cable company.

 Posted by at 11:24 AM

  3 Responses to “Destructuring assignment, part one”

  1. So what happens if you want to return an array? Is the behavior determined by whether you have the var […] structure at the call point?

  2. If you want to return an array, just do:

    var a = f();
    print(a); // prints “Jerry”, 5, true

  3. By the way, if you want to play with this, you can — it’s checked into the JavaScript 1.7 alpha branch. Details on how to check out and build it are available in this article on MDC: