I am trying to fill an array with ranges of values in a recursive function, but i see a weird thing happening while returning the array, though the array has values, when i alert it outside the function it gives me undefined. Not Sure whether its my code issue or any kind of behavior.
Same implementation when i tired using simple for loop it worked fine.
I don't know what title to give for this problem, please suggest me a good one.
With Recursion
var arr = [];
function fillArray(n,i){
if(arr.length !== n){
if(i===0)
arr[i] = i;
else
arr[i] = arr[i-1] + 1;
fillArray(n,++i);
}
else{
console.log(arr);
return arr;
}
}
console.log(fillArray(10,0));
With For Loop
var arr = [];
function fillArray(start,end){
for(var i=start,j=0;i<=end;i++,j++){
arr[j] = i;
}
return arr;
}
alert(fillArray(1,10));