DEV Community

Discussion on: Passing Arrays as Function Arguments

Collapse
 
onashchuk profile image
Alexey Onashchuk

Funny thing that functions like Math.Max internally receive that arguments as arrays (or array-like objects to be precise)

Collapse
 
samanthaming profile image
Samantha Ming

“Array-like”, that’s the keyword. I remember I was so confused when I first encountered that 😅

Collapse
 
toastking profile image
Matt Del Signore

Good ol' this.arguments. My favorite Javascript feature that I'm afraid to use because it doesn't have all the Array methods I want.

Collapse
 
samanthaming profile image
Samantha Ming

It looks like an array, but unfortunately, it isnt :(

Actually, maybe I should write a post about that. The arguments is an interesting topic and I don't think everyone knows that exists 🤔 Even if they knew, the post will be a nice reminder 😂

Thread Thread
 
qm3ster profile image
Mihail Malo

@samanthaming if you end up writing a post on it, I beg of you to include warnings about performance and analysis implications, as well as the "single rest argument"((...args)) alternative.
Honestly, that's the only way I see to offset the damage of more people finding out about/remembering it :D

Collapse
 
qm3ster profile image
Mihail Malo • Edited

AFAIK it causes deoptimization, while (...args) works much better.
Still, if you expect a real array, like in Math's case, you should just take an array.

Math.max(...new Array(200000).fill(1))
Math.max.apply(undefined,new Array(200000).fill(1))

These both fail with a stack overflow, and the only way to get an answer is to implement it yourself:

new Array(20000000).fill(1).reduce((a,b)=>b>a?b:a)