javascript Variable Scope

Microsoft JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.
A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning.
var aCentaur = "a horse with rider,";  // Global definition of aCentaur.

// JScript code, omitted for brevity.
function antiquities()  // A local aCentaur variable is declared in this function.
{

// JScript code, omitted for brevity.
var aCentaur = "A centaur is probably a mounted Scythian warrior";

// JScript code, omitted for brevity.
  aCentaur += ", misreported; that is, ";  // Adds to the local variable.

// JScript code, omitted for brevity.
}  // End of the function.

var nothinginparticular = antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

/*
Within the function, the variable contains "A centaur is probably a mounted Scythian warrior,
misreported; that is, "; outside the function, the variable contains the rest of the sentence:
"a horse with rider, as seen from a distance by a naive innocent."
*/  
It's important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.
var aNumber = 100;
var withAdditive = 0;

withAdditive += aNumber;  // withAdditive is now 100.
tweak();
withAdditive += aNumber;  // withAdditive is now 200.

function tweak()  {
var newThing = 0;  // Explicit declaration of the newThing variable.
// The next statement, if it were not commented out, would generate an error.
// newThing = aNumber;
// The next statement assigns the value 42 to the local aNumber, implicitly declaring it.
aNumber = 42;
if (false)  {
    var aNumber;  // This statement is never executed.
    aNumber = "Hello!";  // This statement is never executed.
    }  // End of the conditional.
}  // End of the function definition.
The statement that is commented out attempts to assign the value of the local variable aNumber to the local variable newThing. It fails, despite the fact that a local aNumber variable is defined elsewhere in the function, and therefore exists throughout. The aNumber variable does not have any assigned value at the point where this statement occurs in the code
Related Posts:
  • Function Call Spacing Almost universally, the recommended style for function calls is to have no space between the function name and the opening parenthesis, which is done to differentiate it from a block statement. For example: // Good doSom… Read More
  • var keyword JavaScript The var and function are declaration statements—they declare or define variables and functions. These statements defineidentifiers (variable and function names) that can be used elsewherein your program and assign values to … Read More
  • Creating Elements, Attributes, and Objects An important benefit of dynamic content is the ability to create new content from freshly received data. This is necessary in dynamic menu creation, navigation, breadcrumbs, and web services, among other applications. Ajax… Read More
  • The try-catch Statement JavaScript provides a try-catch statement that is capable of intercepting thrown errors before they are handled by the browser. The code that might cause an error comes in the try block and code that handles the error goes i… Read More
  • JavaScript Object Literals Object literals are a popular way to create new objects with a specific set of properties, as opposed to explicitly creating a new instance of Object and then adding properties. For example, this pattern is rarely used: … Read More
  • Embedding Content for Plug-Ins Although never officially a part of any HTML specification, the <<embed>> tag is most often used to include embedded objects for Netscape and Internet Explorer. A Macromedia Flash file might be embedded as fo… Read More
  • Reserved Words in JavaScript Reserved Words in JavaScript 1.5 >abstract else instanceof switch >boolean enum int synchronized >break export interface this byte extends long throw case f… Read More
  • JavaScript Form Validation  JavaScript Form Validation. JavaScript can be used to validate data in HTML forms <script type="text/javascript"> function validate_all()     {     var frmReg=document.manageadmin… Read More
  • Javascript Math object The Math object holds a set of constants and methods enabling more complex mathematical operations than the basic arithmetic operators var root = Math.sqrt(10); Constants Provided by the Math Object Property … Read More
  • JavaScript Refresh Page you refresh the page using document.location.reload(). You can add the true keyword to force the reloaded page to come from the server (instead of cache). Alternatively, you can use the false keyword to reload the page from … Read More
  • JavaScript Security Downloading and running programs written by unknown parties is a dangerous proposition. A program available on the Web could work as advertised, but then again it could also install spyware, a backdoor into your system, … Read More
  • JavaScript Dynamic Links and Menus Many sites use JavaScript to create links to other website pages. Here is some examplecode with different link types that you may want to avoid: <HTML><head><title>Link Examples ~ Things to stay away from&l… Read More
  • Expression Statements Assignment statements are one major category ofexpression statements.  For example: greeting = "Hello " + name;i *= 3; The increment and decrement operators, ++ and --, are relatedto assignment statements. These have … Read More
  • Remote JavaScript The primary reason is that the round trip time required to submit a form and then download the response is often inconvenient. The user experience is much improved if, instead of clicking a Submit button and watching the … Read More
  • HTTP “200 OK” response A complete request is not necessarily a successful request, andyour handler for the load event should check the status codeof the XMLHttpRequest object to ensure that you received anHTTP “200 OK” response rather than a “404 … Read More