DEV Community

Discussion on: Demystifying Array.prototype.flat

Collapse
 
bradtaniguchi profile image
Brad • Edited

Does anyone know why the arr.flat() doesn't automatically use Infinity as the default value? Is it a performance thing or something?

Also, could you ever shoot yourself in the foot with this call, or does it protect me from my own shenanigans?

Collapse
 
zakhenry profile image
Zak Henry

could you ever shoot yourself in the foot with this call, or does it protect me from my own shenanigans?

Yep you can shoot yourself in the foot - if for some reason your array contains circular references .flat(Infinity) will cause a stack overflow.

demo:

a = [1,2,3]

b = [4,5,6]

a.push(b)

b.push(a)

a.flat(Infinity) 

// VM185:9 Uncaught RangeError: Maximum call stack size exceeded
//    at Array.flat (<anonymous>)
//    at <anonymous>:9:3
Collapse
 
laurieontech profile image
Laurie

Depends what the shenanigans are! šŸ™ƒ

And to be honest, Iā€™m surprised so many people expected it to be infinity by default?

Collapse
 
rhymes profile image
rhymes

It make sense, flat(N) means I have to know exactly how many levels of nesting there are. We're lazy, Infinity should have been the default :P