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?