Image

variable scope

It's probably obvious to most of you that the following code writes "two" to the screen:

  function changeIt() {
    number = "two";
  }
  var number = "one";
  changeIt();
  document.write(number);


And that if you declare the variable with var inside the function, it'll write "one" instead:

  function changeIt() {
    var number = "two";
  }
  var number = "one";
  changeIt();
  document.write(number);


Here's where it gets a little weird. I discovered by accident today that it doesn't matter where in the function you declare the variable. You can declare it after you assign it, and it keeps the same scope as if you had declared it first. Extending the example above, the following code also writes "one":

  function changeIt() {
    number = "two";
    var number;
  }
  var number = "one";
  changeIt();
  document.write(number);


The declaration works even if the line of code would never be reached during execution:

  function changeIt() {
    number = "two";
    if (false) {
      var number;
    }
  }


On a related topic, you can also call a function at an earlier point in the code than where the function is declared, as long as they're inside the same <script ...> tag. This writes "neato" to the screen:

  howBoutThat();
  function howBoutThat() {
    document.write("neato");
  }