"RangeError: Maximum call stack size exceeded" Why?
Browsers can't handle that many arguments. See this snippet for example:
alert.apply(window, new Array(1000000000));
This yields RangeError: Maximum call stack size exceeded
which is the same as in your problem.
To solve that, do:
var arr = [];
for(var i = 0; i < 1000000; i++){
arr.push(Math.random());
}
Here it fails at Array.apply(null, new Array(1000000))
and not the .map
call.
All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.
You need to the understand what is call stack.
Stack is a LIFO data structure, which is like an array that only supports push and pop methods.
Let me explain how it works by a simple example:
function a(var1, var2) {
var3 = 3;
b(5, 6);
c(var1, var2);
}
function b(var5, var6) {
c(7, 8);
}
function c(var7, var8) {
}
When here function a
is called, it will call b
and c
. When b
and c
are called, the local variables of a
are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.
We implement the callStack as array:
var callStack = [];
Everytime a function called we push the local variables into the stack:
callStack.push(currentLocalVaraibles);
Once the function call is finished(like in a
, we have called b
, b
is finished executing and we must return to a
), we get back the local variables by poping the stack:
currentLocalVaraibles = callStack.pop();
So when in a
we want to call c
again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000))
, your currentLocalVariables
object will be huge because it will have 1000000
variables inside. Since .apply
will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.
Same error happens on infinite recursion(function a() { a() }
) as too many times, stuff has been pushed to the call stack.
Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.