Skip to content Skip to sidebar Skip to footer

Javascript Closure Tutorial From Eloquent Javascript

the question is pretty similar to this thread Javascript..totally lost in this tutorial. function findSequence(goal) { function find(start, history) { if (start =

Solution 1:

The return statement:

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

is an expression involving the "||" operator. That operator will cause the left-hand side to be evaluated. If the result of that is not null, zero, false, or the empty string, then that value will be returned. If it is one of those "falsy" values, then the second expression is evaluated and returned.

In other words, that could be re-written like this:

       var plusFive = find(start + 5, "(" + history + " + 5)");
       if (plusFive !== null)
         return plusFive;
       return find(start * 3, "(" + history + " * 3)")

If "start" ever exceeds "goal", the function returns null. Of course, if both the alternatives don't work, then the whole thing will return null.


Solution 2:

The expression:

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

Will first attempt to evaluate:

find(start + 5, "(" + history + " + 5)")

If the returned value is not null, 0, false, or the empty string then the statement evaluates to the returned value. If the returned value is null, 0, false, or the empty string then the following will be evaluated next:

find(start * 3, "(" + history + " * 3)")

If the returned value is not null, 0, false, or the empty string, then the statement evaluates to the returned value. If the returned value is null, 0, false, or the empty string, then the statement evaluates to null, 0, false, or the empty string (whichever was returned by the *3 function call).

So the line:

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

is like saying "I'm going to try to find the solution by guessing that I add 5 at this step, and if that doesn't work I'll try to multiply by 3 at this step, and if that doesn't work I give up!"


Post a Comment for "Javascript Closure Tutorial From Eloquent Javascript"