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

All About Variable Scope

Now that we’re achieving mastery over functions, another issue becomes important: variable scope. A variable’s scope is made up of the part of the program in which is may be accessed—that is, where it’s “visible” to your code. The scope of variables you declare in one function, for example, are limited to that function, and are not visible in other functions (unless those functions are nested inside the first function).

JavaScript has two types of scope: local and global. When you declare a variable in a function, it’s local to that function, which means its scope is restricted to the body of the function. When you declare a variable in a <SCRIPT> element, outside any function, that variable is global. Any JavaScript code anywhere in the same page as a global variable—inside a function or not—has access to a global variable. If you declare a local variable with the same name as a global variable, however, that local variable overrides the global variable as long as the local variable is in scope. When you leave the local variable’s scope, the global variable resumes its original value.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint