0

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;
}
  • 2
    You're missing `return` on the recursive call. If you don't return what the recursive call returns, the result will be `undefined`. – Pointy Aug 25 '16 at 22:05
  • `return nth(node, num - 1);` – VLAZ Aug 25 '16 at 22:05
  • Because you never do `return nth(node, num - 1);` so the function executes `nth(...)` and then never returns the result of that function. Always define explicit return values everywhere. – Akshat Mahajan Aug 25 '16 at 22:05
  • an alternative: `var arrayToList = arr => arr.reduceRight((rest, value) => ({value, rest}), null);` and `var nth = (list, num) => list /* && num >= 0*/? num? nth(list.rest, num-1): list.value: void 0;` – Thomas Aug 25 '16 at 22:17

1 Answers1

1

You need to return the recursively obtained result:

return nth(node, num - 1);
trincot
  • 317,000
  • 35
  • 244
  • 286