Recursive loops
suggest changeA tail call is the last action in a function. The specification allows an engine to reuse that stack frame. Safari does. Chrome, Firefox, and Node do not, so a long array can still overflow the stack.
function indexOf(array, predicate, i = 0) {
if (0 <= i && i < array.length) {
if (predicate(array[i])) { return i; }
return indexOf(array, predicate, i + 1); // the tail call
}
}
indexOf([1,2,3,4,5,6,7], x => x === 5); // returns index of 5 which is 4
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents