Perfect. So do you understand how steamrollArray([1, [2, 3]])
returns the array [1, 2, 3]
? The first time through the for
loop is just the number 1
, so that is pushed onto flattenedArray
. The second time through the loop we hit the array [2, 3]
and thus we make the recursive call steamrollArray([2, 3])
to make sure it is flattened first so that we can then push it onto flattenedArray
.
We already knew what steamrollArray([2, 3])
returns because we solved it previously. So in a sense, we cheated a little. In a recursive function, it is solved at the time you call it recursively. But the answer is the same. So when we get to the recursive call in the if
block:
flattenedArray.push(...steamrollArray(arr[i]));
The function waits for steamrollArray(arr[i])
to execute and return an answer and then we can push that answer onto flattenedArray
.
The key here is that we know steamrollArray
will always return a flattened array. This may be the hardest part to comprehend. If the current item in the for
loop isn’t an array then it can simply be pushed onto flattenedArray
. But if it is an array, then we recursively call steamrollArray
for that item to make sure it is flattened. In other words, we keep recursively calling steamrollArray
until we have nothing but non-array items in the array we are passing to it. We are drilling down into each sub array until there is nothing but numbers.
I’ll try to clarify with some code.
steamrollArray([1, [2, [3,4]]])
There are two items in this array, the number 1
and the array [2, [3, 4]]
. Don’t let the sub array [3,4]
fool you. The initial array we are passing in only has two items.
First time through the for
loop is the number 1
and so we merely push it to flattenedArray
in the else
block.
Second (and last time through the array) we have the array [2, [3,4]]
and thus we make a recursive call in the if
block.
flattenedArray.push(...steamrollArray([2, [3,4]]))
Don’t let the fact that we are making a recursive call here confuse you. It is as if we are calling a completely different function. Think of it as if we had a function called steamrollArray1
that does the exact same thing as steamrollArray
. So at this point we have to wait for steamrollArray([2, [3,4]])
to return its value. I’m hoping at this point you have a fairly good understanding what will happen there, since it’s basically the same thing as the example we did above (steamrollArray([1, [2,3]])
. Only once steamrollArray([2, [3,4]])
returns its value can we then complete the original line we were left waiting on:
// we are waiting here for steamrollArray([2, [3,4]]) to return a value
flattenedArray.push(...steamrollArray([2, [3,4]]))