Where did my global variable go?

Came accross this problem the other day - thanks to David! Wanted to test if the javascript variable had already been defined (globally) and supply a default value if it wasn't defined.

  var name = "Rob";

  function testScope() {
    document.write("<p>Before IF. My name is " + name + "</p>");
    if (!name) {
      var name = "Rob2";
    }
    document.write("<p>After IF. My name is " + name + "</p>");
  }

  document.write("<p>Before testScope(). My name is " + name + "</p>");
  testScope();
  document.write("<p>After testScope(). My name is " + name + "</p>");

Here is the result.

   Before testScope(). My name is Rob

   Before IF. My name is undefined

   After IF. My name is Rob2
 
   After testScope(). My name is Rob

Unfortunately, simply declaring the var again (var name = "Rob2";) created a locally scoped version of the var for the entire function - even though I only declared it within the IF. The fix was easy: just remove the var.

  var name = "Rob";

  function testScope() {
    document.write("<p>Before IF. My name is " + name + "</p>");
    if (!name) {
      name = "Rob2";  // No var!
    }
    document.write("<p>After IF. My name is " + name + "</p>");
  }

  document.write("<p>Before testScope(). My name is " + name + "</p>");
  testScope();
  document.write("<p>After testScope(). My name is " + name + "</p>");

Here is the result.

   Before testScope(). My name is Rob

   Before IF. My name is Rob

   After IF. My name is Rob

   After testScope(). My name is Rob

It had a value all along!

Remember that global variables belong to the window object, thus the following would also have worked.

  if (!window.name) {
    window.name = "Rob3";
  }

Popular Posts