46

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?

8
  • 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. Commented May 1, 2016 at 15:31
  • The documentation on how to destructure object parameters will certainly also cover how to destructure array parameters. Commented May 1, 2016 at 15:38
  • 3
    @torazaburo then a link to that documentation would be a valid answer to the question Commented May 1, 2016 at 15:43
  • 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. Commented May 3, 2016 at 21:27
  • 1
    I thought exactly the same thing. Endless examples of array assignment destructuring, but almost nothing on array parameter destructuring. Commented Mar 15, 2017 at 0:37

1 Answer 1

51

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

If we want to capture the remaining parameters in the array, we can use rest operator:function foo([a, b, ...args])
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.
Note the second example will output: foo 3 and bar 9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.