Justin Thomas Justin Thomas - 1 year ago 109
Javascript Question

Destructuring in JavaScript 1.7

JavaScript 1.7 allows for destructuring:

[a, b] = [1, 2] // var a = 1, b = 2;

Is there a way to get the rest of the array and head like:

(let [[head & xs] [1 2 3]] (print head xs)) ; would print: 1 [2 3]


a, b* = [1, 2, 3]


Answer Source

Is there a way to get the rest of the array and head in a destructuring assignment?

I don't think so. The spread operator seems to be supported since FF16 in array literals, but the harmony proposal does not yet cover destructuring assignments. If it did, it would look like

[a, ...b] = [1, 2, 3];

Update: ES6 does support this syntax, known as the "rest element" in an array destructuring pattern.

So until then, you will need to use a helper function:

function deCons(arr) {
    return [arr[0], arr.slice(1)];
[a, b] = deCons([1,2,3]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download