81

If I run

Array.apply(null, new Array(1000000)).map(Math.random);

on Chrome 33, I get

RangeError: Maximum call stack size exceeded

Why?

Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
Fabrizio Giordano
  • 2,941
  • 4
  • 20
  • 16
  • What are you actually wanting to do? Fill an array with 1000000 random numbers? Or did you have something else in mind because of `Array.apply`? – Xotic750 Mar 02 '14 at 04:22
  • Yes, I am creating an array of 1,000,000 random numbers. I am using Function.prototype.apply because it doesn't ignore holes. – Fabrizio Giordano Mar 02 '14 at 04:24
  • 3
    Well, you are exceeding the browsers maximum number of supported [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Using_apply_and_built-in_functions) doing it this way. (normally ~65536). A `for` loop would probably be more sensible. – Xotic750 Mar 02 '14 at 04:27
  • 1
    If you are absolutely determined not to use a `for` loop and really want to use `map` then you could use this much slower method (at least I would expect it to be) `Object.keys([].concat(Array(10000001).join().split(''))).map(Math.random)` – Xotic750 Mar 02 '14 at 04:37
  • I wrote a small test: `console.time('object'); var arr = Object.keys([].concat(Array(1000001).join().split(''))).map(Math.random) console.timeEnd('object'); console.time('loop'); var arr = []; var i = 1000000, while(i--){ arr.push(Math.random()); } console.timeEnd('loop');` Object is 2x time faster. – Fabrizio Giordano Mar 02 '14 at 05:01

5 Answers5

88

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());
}
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
35

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.

Community
  • 1
  • 1
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
  • 1
    Thank you for explaining this. I have been struggling to understand why I get this same exception in a method which ironically is recursive, but it occurs with only 1 level deep. Turns out, it wasn't a recursion problem. `Array.prototype.push.apply` was being used and passes an extremely large argument list. It never occured to me that the argument list to the function was too large. I was convinced it was a recursion problem. Thank you again! – Brandon Sep 04 '15 at 20:37
  • Your explanation of stack in JS is half-wrong. In JS functions __b()__ and __c()__ WILL have access to local variables of function __a()__! This is called closures, and this is very important feature of JS. But in general you are explaining concept of stack right way – nned May 03 '16 at 11:15
  • No closures in this example, I didn't want to make it more complicated. – Farid Nouri Neshat Jun 10 '16 at 03:27
18

You first need to understand Call Stack. Understanding Call stack will also give you clarity to how "function hierarchy and execution order" works in JavaScript Engine.

The call stack is primarily used for function invocation (call). Since there is only one call stack. Hence, all function(s) execution get pushed and popped one at a time, from top to bottom.

It means the call stack is synchronous. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. So, basically if everything is running smooth, then at the very beginning and at the end, Call Stack will be found empty.

Here is the illustration of Call Stack: enter image description here

Now, if you provide too many arguments or caught inside any unhandled recursive call. You will encounter

RangeError: Maximum call stack size exceeded

which is quite obvious as explained by others. enter image description here enter image description here

Hope this helps !

Om Sao
  • 7,064
  • 2
  • 47
  • 61
4

The answer with for is correct, but if you really want to use functional style avoiding for statement - you can use the following instead of your expression:

Array.from(Array(1000000), () => Math.random());

The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.

Following the same idea you can rewrite it using ES2015 Spread operator:

[...Array(1000000)].map(() => Math.random())

In both examples you can get an index of the iteration if you need, for example:

[...Array(1000000)].map((_, i) => i + Math.random())

Alexander
  • 7,484
  • 4
  • 51
  • 65
1

In my experience, this error occurred as a result of a recursive function that never terminates. So I put in a condition for which the recursion must stop executing and return (break out). So by adding the line of code below, I was able to get rid of this error.

if (debtTypesCounter === debtTypesLength) return;

So, you can tweak this idea to suit your condition. Hope this helps?