Variables and Scope

  • var means its visible only in the current function. vars declared in an if/else/while/do/other block inside a function are, unlike Java, NOT restricted to that block but to the function that contains that block – this is called hoisting.
  • If you have a local var with the same name as a global variable, and after you initiate that local var you, on a new line, set a new value to that var, then only that local var has the new value and the global variable is unchanged
    myScope = "global";
    (function () {
      var myScope = "function";
      // the line below only changes the local myScope 
      // that was declared in the line above
      myScope = "I set this inside the function";
      alert('inside the function, the scope is: ' + myScope);
    })();
    alert('outside the function, the scope is: ' + myScope);

A global variable is technically (I think) a property of the window object. so

animal = "cat";
console.log(window.animal); // "cat"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s