I’m confused about a solution for a particular problem requiring recursion. I’ll post the problem and then cite my confusion below.
function flattenArray(arr) {
const newArr: string[] = [];
flatter(arr)
function flatter(arr){
arr.forEach((el)=>{
if(Array.isArray(el)){
flatter(el)
} else{
newArr.push(el)
}
})
}
return newArr
}
console.log(flattenArray([[["a"]], [["b"]]]));
console.log(flattenArray([1, [2], [3, [[4]]]]));
This algorithm works, but my confusion is over how. The function flatter
is called before it is created. Within flatter
, it is recursively called again in the if statement. This is twice.
Now, when I removed the first call of the flatter
(the one before its instantiation in the next line) only empty brackets are returned.
I don’t quite I understand why the solution requires this first call of flatter
AND how calling a local function before its instantiation is possible. Why a second call? Isn’t the call of flatter
within the function enough?
Can someone please explain this to me?
Thank you.
I just thought of this…is this an example of closure?