I am going through the grokking algorithms book and trying to wrap my head around recursion. One of the challenges in the book is to "Write a recursive function to count the number of items in a list.". I came up with the following code, which works:
function recursiveArrayCount(arr, count) {
if (arr.length == 0) {
return 0;
} else {
arr.pop();
return count + recursiveArrayCount(arr, count);
}
}
let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray, 1));
My question is, is there a better way to do this in javascript? In particular, I don't like having to seed the value of count with the initial '1' - but I can't think of another way to do it.
pop. That is not nice for the caller of your function, who will find after the call that their array has been destroyed. It is also strange to see code that attempts to count entries in an array without using thelengthproperty (which is the straightforward solution of course), but then still uses that property.