I was just experimenting with some recursion and noticed something that confused me. Let me illustrate with some code examples:
function loop(x) {
if (x >=
function count_to_3 (x) {
x = x || 0;
if (x === 3) { return x; }
return count_to_3(x + 1);
}
count_to_3();
This is the same as saying something like this:
function add_1 (x) { return x + 1; }
function count_to_3 () {
var x = 0;
x = add_1( add_1( add_1(x) ) );
return x;
}
count_to_3();
Each of the add_1
functions are doing their job and returning their value.
The inner function gets called first -- it adds 1
to x
(starting at 0
), and returns its value into the next add_1
, which adds one and returns it into the next add_1
.
...but if you don't return the value, nothings going to happen.
With recursion, it's the same idea.
You're returning the return value of the function you're calling.
You don't need to do this.
Sometimes, recursion is about going through a tree and modifying children -- like changing every second DOM node to red, and changing the first child of every parent node blue...
There's no return value that you need there.
You just need to set up your checks, so that you don't try to recurse into infinity or end up trying to modify properties of things that don't exist.
But for cash registers or for loops where you DO want to know if a value exists, then what you're doing is the same as saying return add_1( add_1( add_1(0) ) );
, assuming that add_1
returns its value.
Any function which doesn't have a return statement will return undefined
(unless it's called with new
, but then you get a new object, and that doesn't help you, either).