Here is a JavaScript example from Eloquent JavaScript:
function findSequence(goal) {
function find(start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
At the very beginning “start” and “goal” in line 3 are not defined. Why does the code not immediately return a result like “undefined” or “ReferenceError: … is not defined”?
line 3 is just part of the function definition. It is not being executed. The second to last line is the one that kicks off the execution. When it is called, the values 1 and “1” are assigned to parameters start and history. goal is referencing the outer function’s parameter. This is populated when the outer function is called.