I have the following code for the nth function in the Chapter 4 exercises in Eloquent JavaScript:
function nth(list, num){
var node = list;
if(num === 0) {
return node.value;
} else {
if (node.rest) {
node = node.rest;
nth(node, num - 1);
} else {
return undefined;
}
}
}
console.log(nth(arrayToList([10,20,30]),1));
// -> 20
I have an iterative version of the function that works as expected; however, this recursive version of the function returns undefined even though a call to console.log right before the return statement correctly prints node.value. Why?
Here is the arrayToList function as well:
function arrayToList(arr){
var list = {value: arr[arr.length - 1], rest: null};
for (var i = arr.length - 2; i >=0; i--){
list = {value: arr[i], rest: list};
}
return list;
}