This is an example from Eloquent Javascript:
By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of
goal
is your objective and it's set to 24
goal == 24
Now we have this internal function find()
that checks to see if start
is equal to 24; its not.
It also checks to see if start is greater then 24 this is also not true,
find(1 "1")
1 == 24 //false
1 > 24 //false
So it hits the else statement where it calls find again, this is where the null value from the else if()
comes in. If the return is null then it calls the || part until it eventually finds the correct answer.
return find(6, "(1 + 5)")
find(11, "((1 + 5) + 5)")
find(16, "(((1 + 5) + 5) +5)")
find(21, "((((1+5) + 5) + 5) +5)")
//next one returns null!
//tries * by 3 on 21, 16, and 11 all return null
so it switches to the ||
return find(3, "(1 * 3)")
find(8, "((1 * 3) +5)")
//some calls down +5 path but that returns null
find(24, "(((1 * 3) + 5) * 3)")
Finally! We have a true return and we have logged the path we took in the history var.