Search code examples
javascriptarraysrecursion

Javascript - recursion/for loop for flattening array


So, here is a sample solution to solve the problem of flattening an array. My question is not 'how' to flatten the array. Rather, I am trying to understand some underlying functionality occurring in this recursion.

This solution goes through each element of the original array, breaking down any elements that are arrays by putting them back through the function until they are no longer arrays and can be pushed to the new array.

My question is, how does the 'for' loop keep track of all of the times that an element is put back through the function, and also continue looping through the rest of the 'original' array that it is working on at the time? It must be keeping track somehow otherwise every time an element is an array and is put back through, the current loop would be cut short. Hope my question makes sense.

function steamrollArray(array) {
  var flatArray = [];

  flatten(array);

  function flatten(array) {
    for (var i = 0; i < array.length; i++) {
      if (Array.isArray(array[i])) {
        flatten(array[i]);
      } else {
        flatArray.push(array[i]);
      }
    }
  }

  return flatArray;
}
steamrollArray([1, [2], [3, [[4]]]]);

Solution

  • I think there will be better answers, but here goes...

    At minimum, don't think of it as "breaking" the loop, think of it as continuing to execute code in a procedural order. So from inside the context of the loop, it calls itself as a function, when that function has completed, it continues in the loop. Example

    var item = [1, [2, 3], 4]
    

    The execution of flatten(item) would be:

    Loop 1: 
      Push 1
    Loop 2: 
      Start a call to flatten with [2, 3]
      Loop 1: 
        push 2
      Loop 2: 
        push 3
      End loop
    Loop 3: 
      Push 4
    End Loop.
    

    So the point is, it is simply executing a procedure of steps. It's not having to "remember" where it was, when a function returns, javascript simply continues to process from where the function was called.

    You may wish to review call stacks.