Why does this program continue to work after returning null?

I study recursion and I understand how the program works, but I am confused why the program continues to work after null returns first when the value at 16 is too large.

Basically, the code will run and add 5 to the argument to run each time from 1.6.11 to 16. Since 16 → 13, it says it returns null. How does JavaScript know to go back and try to compute 13 when it just says it returns null on line 6?

I would really appreciate any help. Here is the code from the book I'm looking at:

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(13)); 
+1
source share
2 answers

The main culprit:

  return find(start + 5, "(" + history + " + 5)") ||
         find(start * 3, "(" + history + " * 3)");

, start 1 , , - 13.

  • find() . A.
  • find() start 1 + 5 (6). Find B.
  • B start 6 + 5 (11). Find C.
  • C start 11 + 5 (16). Find D.
  • D null C.
  • C OR . find() start 6 * 3 (18). Find E.

, ?

  1. E, , , Find D null C.
  2. C null B.
  3. B OR .

, Find A , null, , Find A , , findSolution() .

null find(). null - false. ( history ), find(). history, , , , "", findSolution().


JavaScript.

var findIteration = 0;

function findSolution(target) {
  function find(start, history, caller) {
    var thisIteration = ++findIteration;
    console.log("Find Iteration " + thisIteration, "Start: " + start, "Called by: " + caller);
    if (start == target)
      return history;
    else if (start > target)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)", thisIteration) ||
             find(start * 3, "(" + history + " * 3)", thisIteration);
  }
  return find(1, "1", 0);
}

console.log(findSolution(13));
Hide result

:

Example

"" find(), - , Find C ( 3) Find E ( 5) , .

, find() 9 , , , .

+2

- :

return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");

find() || . returns null. Javascript null false . , find() null, .

+1

All Articles