0

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?

Caleb Jay
  • 2,159
  • 3
  • 32
  • 66
  • 2
    `||` is a [short-circuit operator](https://en.wikipedia.org/wiki/Short-circuit_evaluation). – elclanrs Jan 15 '16 at 16:57
  • 1
    `find()` returns the history, or null. Remember that null is a [falsey](http://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript), 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. – Hanlet Escaño Jan 15 '16 at 17:16

1 Answers1

1

I had a mentor step me through the problem.

When findSolution(target) is called, it calls find(1,"1"). The reason || works is because, if the target is example 24, because (as elclanrs pointed out) || is short circuit, only find(start + 5...) calls will be performed until start = 26. Upon this iteration, start > target, and thus it will return null. The previous call, in which start = 21, will receive a NULL, which || treats as false, which causes it to find(start * 3...), which will also result in a NULL return, which will go back to an iteration in which start = 16, and so on.

Caleb Jay
  • 2,159
  • 3
  • 32
  • 66