Essential Javascript -- A Javascript Tutorial
By Patrick Hunlock2007-12-02
Variable Scope
Variables in Javascript have FUNCTION scope. That is, all variables are global unless they are explicitly defined inside a function and even then child-functions have access to their parent's variables. If a function defines a new variable WITHOUT using the var keyword, that variable will be global in scope.
var global = 'this is global';
function scopeFunction() {
alsoGlobal = 'This is also global!';
var notGlobal = 'This is private to scopeFunction!';
function subFunction() {
alert(notGlobal); // We can still access notGlobal in this child function.
stillGlobal = 'No var keyword so this is global!';
var isPrivate = 'This is private to subFunction!';
}
alert(stillGlobal); // This is an error since we haven't executed subfunction
subFunction(); // execute subfunction
alert(stillGlobal); // This will output 'No var keyword so this is global!'
alert(isPrivate); // This generate an error since isPrivate is private to
// subfunction().
alert(global); // outputs: 'this is global'
}
alert(global); // outputs: 'this is global'
alert(alsoGlobal); // generates an error since we haven't run scopeFunction yet.
scopeFunction();
alert(alsoGlobal); // outputs: 'This is also global!';
alert(notGlobal); // generates an error.
The concept that a variable will continue to exist, and can be referenced after the function that created it has ceased executing is known as CLOSURE. In the above example, stillGlobal, and alsoGlobal can be considered closures because they persist after the function that creates them has ceased to operate. You can do some pretty fancy stuff with it later on, but it's not terribly hard to understand once you associate it with creating a global scoped variable inside a function.
Tutorial Pages:
» Essential Javascript -- A Javascript Tutorial
» Getting Started
» In-Line Javascript
» External Javascript
» Javascript is case sensitive
» Output (writeln)
» Output (alert)
» Output (getElementById)
» Input (One Click To Rule Them All)
» Input (User Input)
» Javascript is an Event Driven Language
» Comments
» Variables
» Variable Scope
» Special Keywords
» Arithmetic Operators
» Logical and Comparison Operators
» JavaScript Conditionals: IF
» JavaScript Conditionals: SWITCH
» JavaScript Conditionals: Shorthand Assignment
» JavaScript Conditionals: Ternary Operators
» JavaScript Loops: FOR
» JavaScript Loops: FOR/IN
» JavaScript Loops: WHILE
» Bringing It All Together
» DHTML: Dynamic HTML
» Conclusion
copyright © 2006, 2007 by Patrick Hunlock
