# Why the array is flatten in my function but it is returned as undefined?

Hi Guys,

So, i made this recursive function where i send again and again an array until it is flatten entirely. But, while my array gets nicely flatten in my function, when i return him outside the function to a varriable, when i log this variable, the result is ‘undefined’:

function flatArray (arr){
let counter=0;
//console.log(arr);
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
arr=arr.flat();
counter=0;
}
else{
counter++;
}
}
if(counter===arr.length){
console.log(arr); // the arr here is nicely flattened
return arr;
}

flatArray(arr);
}

let arr2 = [22,4,[5],5,[2,[2,[2,5,8]]]];
let x = flatArray(arr2);
console.log(x); // here the value is undefined

This gets me crazy!

uhm, i foudn an article about this. I actually need to call the function with the return statement in front. so my code should be like this:

function flatArray (arr){
let counter=0;
//console.log(arr);
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
arr=arr.flat();
counter=0;
}
else{
counter++;
}
}
if(counter===arr.length){
console.log(arr); // the arr here is nicely flattened
return arr;
}

return flatArray(arr);
}

let arr2 = [22,4,[5],5,[2,[2,[2,5,8]]]];
let x = flatArray(arr2);
console.log(x); // here the value is undefined