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?

2
  • 2
    || is a short-circuit operator. Commented Jan 15, 2016 at 16:57
  • 1
    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. Commented Jan 15, 2016 at 17:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.