pineapplecakes pineapplecakes - 1 year ago 43
Javascript Question

Flatten a JavaScript array -- why isn't this working?

I'm trying to flatten an array with randomly nested arrays inside. I'm not sure why the function I wrote ends up in an infinite loop:

let array = [1, 2, [3]]
var final_array = []

function flattener(array){
for(i = 0; i < array.length; i++){
if(array[i] instanceof Array){


What I think SHOULD happen is:

When I'm in the for loop checking for
, it goes into the if statement,
gets called again, it resolves, and then I exit the if statement.

Instead, the if statement keeps calling to check
infinitely, and I'm not sure why this happens.

Answer Source

The problem is you didn't declare the i variable, so it's leaking into the global space and being reset when it recurses.


for(i = 0; i < array.length; i++){


for(var i = 0; i < array.length; i++){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download