Destructuring Assignment with Javascript 1.7

—Friday, July 28 2006

Firefox 2.0 (In beta now) will give us the ability to use Destructuring Assignment. It’s basically the ability for a function to return multiple values while allowing us the capture those values in multiple variables. Do huh?!?

If only it were Ruby

In Ruby, this is pretty sweet:

@closed_tickets, @open_tickets = @tickets.partition &:closed?

Here, closed? is called on all the tickets. If a ticket is closed, it’s put in one batch, and if it’s open, it’s put in another batch. The magic here is that the variable @closed_tickets will only contain those tickets which are closed, and @open_tickets will contain the open tickets.

It turns out Prototype has it’s own partition method. The difference being that we can’t destructure the assignment as we can in Ruby, or we can’t assign the return of partition to multiple variables. We get back an array that contains two more arrays. Take a look at this example:

function isClosed(item) {
  return item == 'closed';
}

var items = "open closed open open closed".split(' ');
var closedOpen = items.partition(isClosed);
console.log(closedOpen);

// We get
//  [["closed","closed"] ["open","open","open"]]
//Note: The word closed seems to be reserved
var close = closedOpen[0];
var opened = closedOpen[1];

Now to get open items, we have to use the correct index. Nasty, but all we really have to work with in the real world for now.

Not quite Ruby, but not quite Javascript 1.6

In the future, we’ll be able to mimic a little bit of the Rubyness of partition because we’ll be able to destructure the assignment. Lets look at what we can do now in Firefox 2.0 Beta (I’ve heard this works in Opera 8+).

var [close, opened] = items.partition(isClosed);
console.log(close, opened);

//We get:
["closed","closed"] ["open","open","open"]

So in this example, partition returned two values which we’re assigned to the correct variables. It’s also good to note that if a function returned 3 values, etc, that you can skip the values you don’t want. So this works:

var [person1, , person3] = ['Justin', 'WillyWonka', 'Rick'];
console.log(person1, person3); // Justin, Rick