A clearer explanation for recursion and flow of execution in JavaScript?

But find didn’t get executed without a value for start and goal. It was first executed with the value 1 for start, and the only value for goal was 24.

Perhaps you’re confused about the order of operations. There we see the declaration of a function, findSequence. During the declaration, no code is executed. The findSequence function only gets executed later, on the last line, where the result of executing the function gets printed out.

Within the declaration of findSequence, there’s a declaration of another function, find. Once again, it doesn’t get executed until later. The findSequence function has just one executable line of code, the one that calls find(1, "1"). Execution of that one line triggers the execution of find some number of times, recursively. The find function makes reference to goal; when the Javascript interpreter executes the code, goal always refers to the parameter of findSequence, and since in this example findSequence is only called once, goal always has the same value, 24.

You should be able to see where the recursion happened. If start was equal to goal, then the function stops; it returns the history of how it arrived at that number. If start is greater than goal, then it returns null, indicating that that path was not a path to the target number. If start is still less than goal, then the function tries calling itself with its start value plus 5. If that returns a non-null value, then that’s what gets returned. Otherwise, it tries multiplying by 3 and returning that history value instead.

Note that although this code can return many numbers, it cannot return all numbers. If the goal is 2, for example, findSequence will return null because there is no way to start at 1 and get to 2 by adding 5 or multiplying by 3.

Leave a Comment