Reputation: 821
This is a partial attempt at solving the Eloquent Javascript challenge in Chapter 4, A List. theArray returns undefined, but if I just print its value it is what I would expect (An array of values). Why does it return undefined?
var obj = {"value":"C","rest":{"value":"B","rest":{"value":"A"}}};
var theArray =[];
var listToArray = function(list) {
theArray.push(list.value);
if(list.rest !== undefined) {
listToArray(list.rest);
} else return theArray; //console.log(theArray); returns the expected value
}
console.log(listToArray(obj));
Upvotes: 2
Views: 530
Reputation: 67207
You have to return the recursive call,
if(list.rest !== undefined) {
return listToArray(list.rest);
If you do not return the recursive call, then the array
which is from the final function stack will not be returned instead undefined
will be returned.
Upvotes: 3