22

There is plenty of documentation on how to destructure objects passed as function parameters in Javascript 2015 / ES6 / ECMAScript 2015, with a function like this:

function foo({a, b}) {
   console.log(`a: ${a}, b: ${b}`);
}

But how do you destructure an array parameter?

JBCP
  • 11,766
  • 6
  • 67
  • 107
  • 3
    Honest question: Why is this downvoted? I had trouble finding a straight answer to this question either on SO or on the general internet, and I believe syntax questions are legitimate for SO. – JBCP May 01 '16 at 15:31
  • The documentation on how to destructure object parameters will certainly also cover how to destructure array parameters. –  May 01 '16 at 15:38
  • 3
    @torazaburo then a link to that documentation would be a valid answer to the question – JBCP May 01 '16 at 15:43
  • @JBCP: Can you link the documentation that you found that only covers objects? – Bergi May 01 '16 at 15:56
  • Here's an example of arrays being destructured: http://stackoverflow.com/q/3986348/1048572 – Bergi May 01 '16 at 15:56
  • This certainly covers all the issues: http://exploringjs.com/es6/ch_destructuring.html –  May 01 '16 at 16:01
  • 1
    Ok, buried in two lines of that documentation (10.1.3 Where can destructuring be used?) there is an example of an array being destructured as a function parameter. I still think it is a legitimate question since although the syntax might be obvious, the documentation is not explicit, and having to read the language specification is not always reasonable. – JBCP May 03 '16 at 21:27
  • 1
    Not sure why downvoted, but I upvoted. – trusktr Mar 14 '17 at 20:52
  • @trusktr thanks - I don't think this information is easily found, at least not when I originally asked it – JBCP Mar 14 '17 at 21:34
  • I thought exactly the same thing. Endless examples of array assignment destructuring, but almost nothing on array parameter destructuring. – trusktr Mar 15 '17 at 00:37

1 Answers1

25

The correct syntax to destructure an array parameter is:

function foo([a, b]) {
   console.log(`param1: ${a}, param2: ${b}`);
}

It can be called like this:

 foo(['first', 'second']);
 // Will output:
 // param1: first, param2: second

According to Exploring ES6, section 11.6, you can use this to destructure parameters within arrow functions as well:

const items = [ ['foo', 3], ['bar', 9] ];
items.forEach(([word, count]) => {
    console.log(word+' '+count);
});
JBCP
  • 11,766
  • 6
  • 67
  • 107
  • 1
    If we want to capture the remaining parameters in the array, we can use rest operator:`function foo([a, b, ...args])` – Ahmad Ferdous May 01 '16 at 05:53
  • Thank you. I had it right for my part, but I had other issues that were causing void to be passed into each element of my array. (`map` instead of `tap` in rxjs). So I thought I had it wrong. – RoboticRenaissance Feb 04 '21 at 21:57