DEV Community

Discussion on: Passing Arrays as Function Arguments

Collapse
 
qm3ster profile image
Mihail Malo • Edited

This is problematic because it goes on the stack.

const bite1 = arr => {
  const [head, ...tail] = arr
  if (tail.length === 0) return "⚰"
  return bite1(tail)
}
console.log(bite1(new Array(2000))) // Success

const biteV = (...args) => {
  const [head, ...tail] = args
  if (tail.length === 0) return "⚰"
  return biteV(...tail)
}
console.log(biteV(...new Array(600))) // DIES

In both cases we are iterating immutably and using lots of memory, but the second runs out of stack space while the first doesn't. (And mere 600 is far from a ridiculous number!)