Before I get to the meat of my question, here is the code that goes before the area in question.
function arrayToList(array) {
var list = null;
for (var i = array.length - 1; i >= 0; i--)
list = {value: array[i], rest: list};
return list;
}
function listToArray(list) {
var array = [];
for (var node = list; node; node = node.rest)
array.push(node.value);
return array;
}
Now, can someone explain the difference between calling a function and returning a function. When I call my function, I get undefined for my result. However if I return my function, the answer is correct. Can someone explain to me the difference between the two?
With the return:
function nth(list, n) {
if (!list)
return undefined;
else if (n == 0){
return list.value;
}
else
return nth(list.rest, n - 1);
}
Without the return:
function nth(list, n) {
if (!list)
return undefined;
else if (n == 0){
return list.value;
}
else
nth(list.rest, n - 1);
}
Thanks for your help!
If you don't return anything then the variable awaiting the function call will be undefined. When you return a function call you are returning the result of that execution. When you just execute the function you are not returning the results of that execution. Let me show you an example: Fiddle
IF you are trying to return a function to be called later, than can be done too, but you need to return the name of the function without the parenthesis. See here: Fiddle
Here is the full code sample with everything mentioned above: