Are you curious about how many recursive calls can be made by the JavaScript engine?
How many recursive calls
The following function allows you to find the answer: (Inspired by Ben Alman's gist)
The code copy is as follows:
function computeMaxCallStackSize() {
try {
return 1 + computeMaxCallStackSize();
} catch (e) {
// Call stack overflow
return 1;
}
}
Three results:
The code copy is as follows:
Node.js: 11034
Firefox: 50994
Chrome: 10402
What do these numbers represent? Mr. Aleph pointed out that in V8, the number of recursive calls depends on two quantities: the size of the stack and the size of the stack frame (the local variable that holds the parameters). You can verify that by adding local variables in computeMaxCallStackSize() - it returns a low value.
Tail call optimization in ECMAScript 6
ES6 has tail call optimization: if the last step in a function is also a function call, it will be "jumped" instead of being called by a subfunction. This means that in ES6 (strict mode), you just need to change the computeMaxCallStackSize function a little, and it can be executed forever.
The code copy is as follows:
function computeMaxCallStackSize(size) {
size = size || 1;
return computeMaxCallStackSize(size + 1);
}