# Recursive question

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?

this is a feature of how the function is defined. Defining the function in that way, with `function funcName () {}` you can call the function before declaring it.
see here: https://stackoverflow.com/questions/261599/why-can-i-use-a-function-before-its-defined-in-javascript

if you never call `flatter`, then `newArr` is never changed and you just return its starting value

if you never call the outer function then the function call inside that function never execute…

``````function func1 (where) {
console.log("Function 1 called " + where);
}
function func2 (where) {
func1("inside func2");
console.log("Function 2 called " + where);
}
``````

`func1` is being called inside `func2`, but it you don’t call `func2`, will `func1` ever be called? try yourself.
this is the same even if it is recursive. (if you want to try, be sure to give a stopping condition or there will be stack overflow)