eric
eric

Reputation: 3

Undefined variables in JavaScript

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"?

Upvotes: 0

Views: 111

Answers (3)

Adam Dymitruk
Adam Dymitruk

Reputation: 129744

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.

Upvotes: 1

Useless Code
Useless Code

Reputation: 12422

They don't result in errors because by line 3 they are both defined. In JavaScript function parameters are implicitly defined as local variables inside of that function. That is why start is defined and initialized with the value that was passed as the first argument when find is invoked. In the same way goal was defined on line 1 in the function statement that created the findSequence function. goal is accessible inside of the find function via closure. It is a little more complicated but for the purpose of this example, closure means that when a function is defined inside of another function it has access to variables that belong to the parent functions scope.

If you want to learn more about closures (which would be a good idea if you will be writing a lot of JavaScript code) checkout Closing the book on JavaScript Closures, it is a pretty good article about closures. I haven't read the whole thing but this FAQ seems to be quite good too.

Stuart Langridge gave a great lecture called Secrets of JavaScript Closures at the Fronteers Conference '08: Part 1, Part 2

Upvotes: 0

pradeek
pradeek

Reputation: 22115

start and goal are the arguments to the find and findSequence functions in lines 1 and 2

Upvotes: 0

Related Questions