4

I have a function that takes a variable number of parameters and I have those parameters in an array. The function doesn't take the array as a parameter. What I want to do is destructure the array into the arguments of the function call. I am not sure how long the array is but I know it will be more than 3.

var array = ['a', 'b', 'c', 'd', ...etc]
doit(arr[0], arr[1], arr[2], ...etc)

function doit( a, b, ...c){
  //do stuff
}
1
  • “The function doesn't take the array as a parameter.” Is that by design, or would you be willing to accept an array parameter? Do the parameter variables need distinct names (a, b, c etc) or would an array do? What version JavaScript do you have available? Commented Aug 17, 2020 at 5:55

2 Answers 2

5

Sounds like you should just spread array into the call of doit:

doit(...array);

Note that this is called spread (or "spread syntax"), which is not destructuring. Destructuring involves either creating a new variable, or assigning to an existing variable.

The older method would be to use apply:

doit.apply(undefined, array);
Sign up to request clarification or add additional context in comments.

3 Comments

@ CapitalJusticeWarrior - With your existing declaration (function doit(a, b, ...c)), which is valid even if you may have just meant it as shorthand, if you do the above you'd get the first array element as a, the second as b, and the rest of them in as an array in c (that declaration for c is called a rest parameter).
Thanks! I was only thinking of using the spread within array brackets.
@CapitalJusticeWarrior Note that compatibility, while high, is not uniform, see MDN and for rest too. (Probably not an issue if spread works in your process already, but you might consider Babel just to be safe, if you aren't already, if you want to support ancient browsers)
-1

One way would be to use the special variable arguments inside any javascript function. You will gain access to all arguments, regardless of their count.

var arr1 = ['a', 'b', 'c', 'd', 'e', 'f'];
var arr2 = ['A', 'B', 'C'];

doit(arr1);                               // one argument: [a,b,c,d,e,f]
doit(arr2);                               // one argument: [A,B,C]
doit(arr1[0], arr2[1], 'anything', -3.1); // four arguments: a, B, 'anything', -3.1

function doit(){
  for(var i=0; i<arguments.length; i++) {
    console.log("argument " + i + " is : " + arguments[i]);
  }
}

1 Comment

The question asks how to destructure, not how to access by index operator which will not work for an array of unknown length. It is also not asking how to handle an unknown number of arguments in a function.

Your Answer

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