In Eloquent Javascript, the following example is given as a recursive function:
function findSolution(target) {
function find(start, history) {
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(24));
A good explanation is given after, but I'm having trouble understanding why the
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
bit works. Why can you have an || without, it seems to me in any case, a boolean being worked on? How does find() know to "come back" and to this part of the function and "try again" with start * 3 when it gets to a branch in which start > target and thus is given a null?
||is a short-circuit operator.find()returns the history, or null. Remember that null is a falsey, so it will evaluate to false, and if the function does not return null, but a history it will return true (truthy value). That's why it can evaluate and return true or false. As mentioned above,||is a short-circuit operator. Meaning that if the expression to the left of the||evaluates to true, it won't evaluate the expression to the right. The way it 'knows' where/how to come back, you will need to read a little about call stacks in JS.