Too Many Arguments in JavaScript

How many are too many?

Too Many Arguments in JavaScript

In the short example below, JavaScript engine is complaining about too many arguments to Math.max().

> const longArray = Array(10000000);
undefined
> longArray.fill(0);
[
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0,
  ... 9999900 more items
]
> Math.max(...longArray)
Uncaught RangeError: Maximum call stack size exceeded
Example with Node.js v15.14.0.

It seems there is an upper limit for the number of arguments you can pass to a function.

The consequences of applying a function with too many arguments (that is, more than tens of thousands of arguments) varies across engines. (The JavaScriptCore engine has hard-coded argument limit of 65536.

Here is a safe way to calculate the maximum value in an array.

const max = arr.reduce((max, v) => Math.max(max, v), 0);

Reference

Function.prototype.apply() - JavaScript | MDN
The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).