-1

I'm working through the book Eloquent JavaScript. One of the exercises asks you to create a recursive function that returns the nth value in a list, of the format:

var list = {value: 10, rest: {value: 20, rest: {value: 30, rest: null}}};

I've since viewed and understood the author's solution (and I now realise I actually didn't need an inner function!) but I'm still curious as to why my code doesn't work:

function nth(list, num){
    var count = 0;
    function findNum(node){
        if(count == num){
            var result = node.value;
            console.log("From inner function: " + result);
            return result;
        }else {
            node = node.rest;
            count++
            findNum(node);
        }
    }
    var output = "From outer function: " + findNum(list);
    return output;
}

I've researched the answer here and I appear to be doing the right thing to return from the inner function, however I get the following results when the outer function is called:

console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 0));
//From inner function: 10
//From outer function: 10

console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 1));
//From inner function: 20
//From outer function: undefined

console.log(nth({value: 10, rest: {value: 20, rest: {value: 30, rest: null}}}, 2));
//From inner function: 30
//From outer function: undefined

My question is: why does the outer function return as intended when looking for the first value but return as 'undefined' in the other two cases?

Community
  • 1
  • 1
CJ1138
  • 1
  • Yeah I found a few answers about the exercise but I couldn't see one that addressed this particular problem – CJ1138 Jan 16 '17 at 11:57
  • Nothing that could not be solved by simply walking through your code in the debugger watching what it does. –  Jan 16 '17 at 12:06

1 Answers1

-1

findNum object returns a value only if the if statement matches.

In the else side, it calls findNum recursively but ignores the return value you get back from that call.

You have to return what you get back from recursively calling findNum

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335