Destructuing assignment in ECMAScript 6 is my new favorite feature

I recently attended an SFHTML5 meetup where Kit Cambridge gave a talk on some of the new features coming to ECMAScript 6, the next version of the JavaScript specification. There are a lot of exciting new features coming, but far and away my favorite is destructuring assignments.

I always really liked how Python could return tuples from methods and you could assign them to tuples of variables and just use them. Well, destructuring assignments in JavaScript are a much more powerful version of the same thing. Let's start with a simple example:

let [a, b] = ['Hank', 'Dean'];

console.log(a); // Hank  
console.log(b); // Dean  

Here I am using the new 'let' keyword (block-scoped equivalent to 'var') to assign to variables, a and b, to the first and second entry of an array, respectively. It mimics how tuples work in Python very closely, and means that no longer do we have to do this:

function getDetectiveInfo() {  
    return [{
        name: 'Hank Venture',
        age: 'It\'s complicated'
    }, {
        name: 'The Alchemist',
        age: 'Redacted'
    }];
}

var detectives = getDetectiveInfo(),  
    hank = detectives[0],
    al = detectives[1];

console.log(hank.name); // Hank Venture  
console.log(al.name); // The Alchemist  

because we can instead do this:

function getDetectiveInfo() {  
    return [{
        name: 'Hank Venture',
        age: 'It\'s complicated'
    }, {
        name: 'The Alchemist',
        age: 'Redacted'
    }];
}

let [hank, al] = getDetectiveInfo();

console.log(hank.name); // Hank Venture  
console.log(al.name); // The Alchemist  

Pretty neat. It gets much better though, because we can also destructure objects!

let { name: myname, occupation: myoccupation } = {  
    name: 'The Monarch',
    occupation: 'Arching Dr. Venture'
};

console.log(myname); // The Monarch  
console.log(myoccupation); // Arching Dr. Venture  

I can already see how much more concise and readable code will be when dealing with REST calls, JSON parsing, and working with third party libraries in general. When combined with iterators, another new ECMAScript 6 feature, iterating over arrays of objects will become considerably easier. For example:

var villians = [{  
    name: 'The Monarch',
    realName: 'Malcolm'
},{
    name: 'Baron Ünderbheit',
    realName: 'Werner Ünderbheit IV'
},{
    name: 'Phantom Limb',
    realName: 'Hamilton G. Fantomos'
}];

// The Monarch is actually named Malcolm
// Baron Ünderbheit is actually named Werner Ünderbheit IV
// Phantom Limb is actually named Hamilton G. Fantomos
for (let {name: n, realName: r } of villians) {  
    console.log(n + ' is actually named ' + r);
}

So yeah, this stuff is awesome! I love it because it will make my code more readable, concise, less error prone, and possibly even more efficient since we don't have to allocate a temp variable. I can't wait for it to become mainstream.