Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RangeError: Maximum call stack size exceeded with array.push(...)

Tags:

javascript

The simple code below produces RangeError: Maximum call stack size exceeded

const arr = []
for (let i = 0; i < 135000; i++) {
    arr.push(i)
}
const arr2 = []
// something else here that changes arr2
arr2.push(...arr)

1) Why does this happen? (I am simply adding element to an array, why does it increase stack size ?)

2) How to fix this error ? (My goal is to create a shallow copy of arr into arr2)

like image 373
TSR Avatar asked May 11 '20 22:05

TSR


People also ask

How do I fix error RangeError maximum call stack size exceeded?

The most common way to fix this error is to reduce the number of function calls, or to limit the number of variables that are created. Another option is to use a tracer debugger to keep track of the program's state and find the function that's causing the error.

What does error RangeError maximum call stack size exceeded see Javascript console for details mean?

The "RangeError: Maximum call stack size exceeded" error occurs when a function is called so many times that the invocations exceed the call stack limit. To solve the error, specify a base case that has to be met to exit the recursion.

What is maximum call stack size exceeded error?

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. This is almost always because of a recursive function with a base case that isn't being met.

What is Javascript maximum call stack size?

Without any local variables, each function call takes up 48 bytes during the execution, and you are limited to less than 1MB for all local function frames. Each boolean and number variable takes 8 bytes of memory.


1 Answers

The spread operator there pushes all elements in the original array into the stack, just like .apply:

const arr = [];

for (let i = 0; i < 10; i++) {
  arr.push(i);
}

const arr2 = [];

// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

Array.prototype.push.apply(arr2, arr);

console.log(arr2.join(', '));

So the amount of data you can handle in both cases is limited by the stack size:

const arr = [];

for (let i = 0; i < 135000; i++) {
  arr.push(i);
}

const arr2 = [];

// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

Array.prototype.push.apply(arr2, arr);

console.log(arr.length, arr2.length);

You could do this instead:

const arr = [];

for (let i = 0; i < 135000; i++) {
  arr.push(i);
}

let arr2 = [];

// Something else here that changes arr2:
arr2.push(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

arr2 = [...arr2, ...arr];

console.log(arr.length, arr2.length);
like image 108
Danziger Avatar answered Oct 20 '22 05:10

Danziger