DEV Community

Discussion on: How many ways iterate the objects and arrays in javascript?

Collapse
 
lexlohr profile image
Alex Lohr

I knew I forgot something :-)

In any case, you won't be fine if the lenght of the array exceeds the one of the call stack.

Thread Thread
 
qm3ster profile image
Mihail Malo

Nuh-uh, bronathan! In fact, I assume that the logic / base case of the handling is void-returning.
The return here is purely to opt in to tail call optimization, which means you won't run out of stack :)
Once again, only implemented on Apple browsers at the moment, and probably staying that way.

Thread Thread
 
lexlohr profile image
Alex Lohr

Your misunderstanding might be resolved if you take the following as an example:

const array = new Array();
array.length = 1/0;
...

An extreme example, I concede, but as an exercise, you can try to figure out the call stack sizes for different JS engines (and AFAIK they're all smaller than the maximum number the 52bit mantissa of a Number can store).

Thread Thread
 
qm3ster profile image
Mihail Malo • Edited

Optimized tail calls don't grow the stack.

They're implemented with a goto, it's basically a loop.


{
  let i = 0
  const rec = () => (i++, rec())
  try {
    rec()
  } catch {}
  console.log(i)
}

On most browsers this will give you a number.
On Safari, Mobile Safari, and some embeddable runtimes like latest Duktape It will be an infinite loop.