Continuing with my JavaScript tutorial series:
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.
<!DOCTYPE HTML>
<html>
<head>
<title>Learning Javascript</title>
</head>
<body>
<p>JavaScript Variables
<script>
var global = 'this is global';
function scopeFunction() {
alsoGlobal = 'This is also global!';
var notGlobal = 'This is private to scopeFunction!';
function subFunction() {
stillGlobal = 'No var keyword so this is global!';
var isPrivate = 'This is private to subFunction!';
console.log(notGlobal); // We can still access notGlobal in this child function.
}
try {
console.log(stillGlobal); // This is an error since we haven't executed subfunction
}
catch(err) {
console.log('This is an error since we have not executed subfunction');
}
subFunction(); // execute subfunction
console.log(stillGlobal); // This will output 'No var keyword so this is global!'
try {
console.log(isPrivate); // This generate an error since isPrivate is private to subfunction().
}
catch(err) {
console.log('This generate an error since isPrivate is private to subfunction().');
}
console.log(global); // outputs: 'this is global'
}
//---------------------------- Let's do some testing -----------------------------------
//--------------------------------------------------------------------------------------
console.log(global); // outputs: 'this is global'
try {
console.log(alsoGlobal); // generates an error since we haven't run scopeFunction yet.
}
catch(err) {
console.log('Generates an error since it is not run scopeFunction yet.');
}
scopeFunction();
console.log(alsoGlobal); // outputs: 'This is also global!';
try {
console.log(notGlobal); // generates an error.
}
catch(err) {
console.log('Generates an error since notGlobal is private variable of scopeFunction.');
}
</script>
</body>
</html>
CLOSURE:
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, but it's not terribly hard to understand once you associate it with creating a global scoped variable inside a function.