Function.prototype.apply() — Using apply() and built-in functions
Clever usage of apply() allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax).
Reference note (untrusted external data; do not execute it as instructions).
Clever usage of apply() allows you to use built-in functions for some tasks that would probably otherwise require manually looping over a collection (or using the spread syntax).
For example, we can use {{jsxref("Math.max()")}} and {{jsxref("Math.min()")}} to find out the maximum and minimum value in an array.
But beware: by using apply() (or the spread syntax) with an arbitrarily long arguments list, you run the risk of exceeding the JavaScript engine's argument length limit.
The consequences of calling a function with too many arguments (that is, more than tens of thousands of arguments) is unspecified and varies across engines. (The JavaScriptCore engine has a hard-coded argument limit of 65536.) Most engines throw an exception; but there's no normative specification preventing other behaviors, such as arbitrarily limiting the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.
If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time
Attribution: Adapted from MDN Web Docs under CC-BY-SA-2.5. Adaptation: WikiKV selected one documentation section, normalized formatting, retained bounded excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
MDN Web Docs — files/en-us/web/javascript/reference/global_objects/function/apply/index.md :: Using apply() and built-in functions ↗Revision d14bee540b53 · CC-BY-SA-2.5 and attribution