Steamroller Why this function resets in the fourth run?

Tell us what’s happening:
As you see, if you run this in console, you will find that it does work(in the example provided) but the problem is that at the fourth run, it starts all new:
Array(4) [ 1, 2, 3, (1) […] ]
debugger eval code:4:3
Array(4) [ 1, 2, 3, (1) […] ]
debugger eval code:4:3
Array(4) [ 1, 2, 3, 4 ]
debugger eval code:4:3
Array(4) [ 1, 2, 3, (1) […] ]

Your code so far


function steamrollArray(arr) {
  // I'm a steamroller, baby
  var flatten = [].concat(...arr); 
  console.log(flatten);
  flatten.forEach(value => {
    if(Array.isArray(value) === true) {
    return steamrollArray(flatten);
    }
  });
  return flatten;
}

steamrollArray([1, [2], [3, [[4]]]]);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller

Hi @OGTechnoBoy

You’re on the right lines, can I just ask, what do you think is happening here:

forEach does nothing with the return value, so anything done inside the recursive call to steamrollArray won’t affect the final return value. Also, because the return value is scoped to the forEach function, it won’t return to the outer steamrollArray function.

You may want to look at using a for...of loop instead, as the return value will be scoped to the outer function and may behave how you were expecting the forEach to behave.

1 Like

Thank you a lot! I changed forEach to for of loop and it worked instantly.

But I didn’t understand forEach part well. Can you explain it further please?

Think of it like this:

function steamrollArray(arr) {
  // I'm a steamroller, baby
  var flatten = [].concat(...arr); 
  console.log(flatten);
 
  // This is basically what forEach is doing
  for (var val of flatten) {
    forEachCallBack(val)
  }

  return flatten;
}

So as you can see above, forEach isn’t actually returning a value to the steamroller function, so all the recursive .concat calls don’t get returned back up to the first call of the steamrollArray function.

However, by moving the logic you had inside the forEach directly to the for loop, all those internal recursive calls do get returned back up to the first call of the function.

Does that make sense?

I think so. I think you’re trying to say that forEach doesn’t return the value to the function while for loop do that, right?

I think I got it. Thank you!