Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

7. Scope and Closures > Use var Inside Functions to Declare Variables and Avoid...

Use var Inside Functions to Declare Variables and Avoid Scope Gotchas

JavaScript will declare any variables lacking a var declaration (even those contained in a function or encapsulated functions) to be in the global scope instead of the intended local scope. Have a look at the code below and notice that without the use of var to declare bar, the variable is actually defined in the global scope and not the local scope, where it should be.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var foo = function() {
    var boo = function() {
        bar = 2; /* no var used, so bar is placed in the global scope 
                  at window.bar */
    }();
}();

console.log(bar); // logs 2, because bar is in the global scope

// As opposed to...

var foo = function() {
   var boo = function() {
       var doo = 2;
   }();
}();

console.log(doo); /* logs undefined, doo is in the boo function scope, 
                  error occurs */

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint