Here are a couple of issues that need to be addressed:
- You may exceed the call stack limit
- Your if statement is not correctly configured
Regarding the first problem:
If you have a large list, it's possible to surpass the call stack limit when making recursive calls for each element. While using setTimeout
could be a workaround, it seems like a makeshift solution. The root issue lies in handling the array recursively instead of iteratively within your function. I suggest rewriting your function with a for loop.
For the second problem:
Consider an array like [100, 90, 80]
. On the third invocation of nextArrayItem()
, you end up popping off the last element (in this case 100
). Since 100
is truthy, the if statement passes mistakenly, leading your function to recurse despite an empty array. The program should exit the call stack at this point.
I tested your code scenario in Chrome and noticed an extra recursion resulting in a pop operation on an empty array, yielding undefined.
To resolve this, modify the if condition to verify the last element post-pop:
Updated code snippet:
var nextArrayItem = function() {
var grade = array1.pop();
if (array1[array1.length-1]) {
nextArrayItem();
}
};