Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest array I can safely pass to function.apply() / spread operator

The "JavaScriptonic" way to calculate the maximum value of an array is:

Math.max.apply(null, array)

However, this errors with "maximum call stack size exceeded" on arrays of size 2^16 (Chrome, Safari) or 2^18 (Firefox). See https://jsfiddle.net/dxcot206/

How can I use this technique safely? Is there a largest array length for which this technique is guaranteed to work?

Might the answer be different in a WebWorker, since background threads often have smaller stack sizes?

like image 847
ridiculous_fish Avatar asked Jun 04 '26 07:06

ridiculous_fish


1 Answers

How can I use this technique safely?

Not at all.

Is there a largest array length for which this technique is guaranteed to work?

No, there are no requirements for such things in the spec, all you are seeing are implementation-dependent "we don't support unreasonably large argument lists above N" restrictions.

The "JavaScriptonic" way to calculate the maximum value of an array is: Math.max.apply(null, array)

It's just short, but not very efficient, and as you have seen might not work. Better use array.reduce((a, b) => Math.max(a, b)).

like image 188
Bergi Avatar answered Jun 06 '26 20:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!