Languages

JavaScript - array.push(...items) causes "Uncaught RangeError: Maximum call stack size exceeded"

8 points
Asked by:
Alicia-Lambert
580

Today, working with Preact, I have noticed the exception caused by push() used with spread syntax (...).

I have decided to repeat the test on the simpler case, ao the script that I have tested under Google Chrome 97.0.4676:

<script>

	const array = Array(500000).fill(0);
	const backup = Array();

	backup.push(...array);

	console.log(array.length);
	console.log(backup.length);

</script>

Exception:

push_test.htm:6 Uncaught RangeError: Maximum call stack size exceeded
    at push_test.htm:6

Screenshot:

Uncaught RangeError: Maximum call stack size exceeded
Uncaught RangeError: Maximum call stack size exceeded

Any ideas why it is not permitted to add items this way? Is there some recurrence inside?

1 answer
7 points
Answered by:
Alicia-Lambert
580

In JavaScript, functions have a limited number of the arguments per call.

In above case array.push(...items) passes big amount of aruments during call.

It is the same case as you are not able to use array.push.apply(array, items) function call passing items array - same problem.

Try to use loops:

<script>

	const array = Array(500000).fill(0);
	const backup = Array();

	for (let i = 0; i < array.length; ++i)
		backup.push(array[i]);

	console.log(array.length);
	console.log(backup.length);

</script>

Preview:

Array push() with loop.
Array push() with loop.
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join