Suppose I have this simple JavaScript function:
function returnArray(){
return [1, 2, 3];
}
Further suppose that I then say
var test = [0, ...returnArray()];
You'd expect test to be equal to [0,1,2,3], and you'd be right. I tried that and of course it works.
Now I have this exercise where I'm suppose to build a function called double that takes an array as a parameter and returns another array that contains all of the original array's values doubled. So if I call double([1,2,3]) I should get [2,4,6]. The constraints of the exercise are that I must use only array destructuring, recursion, and the rest/spread operators to build my function. No array helpers allowed. So I came up with this:
function double(array){
if (array.length===1) return 2*array[0];
var [num, ...rest] = array;
if (rest.length!=0) return [2*num, ...double(rest)];
}
If I run this function with any array whose size is at least two, I receive an error message saying that double is not a function. If I remove the ... operator before double, magically double is a function again, except that of course the result of double([1,2,3]) is [2,[4,6]], which is not quite the same as [2,4,6].
My first thought was that maybe, for some weird reason, you can't use ... in front of a function, even if the function returns an array, so I tested this hypothesis with my the returnArray() function above, and found out that it works just fine. I have no idea why it breaks down in the exercise. I can only guess recursion might have something to do with it, but I have no clue why it would be so. Can anyone point out what's wrong my my code?
EDIT: Thanks everyone, it was quite a silly mistake! I should have seen it. I added comments to some of your answers.