Global area
When something globally means that it is available from anywhere in your code. Take this for example:
var monkey = "Gorilla";
function greetVisitor () { return alert("Hello dear blog reader!"); }
If this code was run in a web browser, the function area would be a window, which would make it
available for everything that works in this web browser window.
Local area
Unlike a global scope, a local scope is when something is simply defined and available in
a certain part of the code, as a function. For instance,
function talkDirty () {
var saying = "Oh, you little VB lover, you"; return alert(saying); } alert(saying);
If you look at the code above, the variable message is only available in talkDirty
function. Outside of this, it is not defined at all. Please note: if you said you didn’t say
The var keyword is before it; it will automatically become a global variable.
It also means that if you have nested functions, the inner function will have access to
contains functions and function functions:
function saveName (firstName) {
function capitalizeName () {
return firstName.toUpperCase();
} var capitalized = capitalizeName ();
return capitalized;
}
alert(saveName("Robert")); // Returns "ROBERT"
As you just saw, the internal capitalizeName function did not need any parameter that was sent, but had a complete
access to the firstName parameter in the external saveName function. For clarity, let's take another
Example:
function siblings () {
var siblings = ["John", "Liza", "Peter"];
function siblingCount () {
var siblingsLength = siblings.length; return siblingsLength;
}
function joinSiblingNames () {
return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n");
}
return joinSiblingNames();
}
alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"
As you just saw, both internal functions have access to an array of siblings in the containing function, and
each internal function has access to other internal functions at the same level (in this case
joinSiblingNames can access siblingCount). However, the siblingsLength variable in siblingCount is
available only in this function, i.e. in this area.