Your first example is flawed because of the use of document.write
. When you use that AFTER a document has been built, it wipes out the earlier document and writes a new one. The results you were seeing from the first example were distorted by this.
Really, your examples are just demonstrating Global vs. Function scope in JavaScript. Anything declared with var
in a function has local scope to that function and will be removed from memory when the function it is declared within terminates or is no longer held in memory.
Take a look at the comments I've added to your slightly modified code:
// We are going to replace all the document.write() calls with
// console.log() calls because you are experiencing information being
// written to the document and then the document is being overwritten
// with new information.
// The result will be "global, local" because the code in "myFunction" is
// not going to run until the window is loaded. The last line of code in
// this example will actually run first.
window.onload = myFunction;
var go="global"; // Just declare a Global variable (available everywhere)
function myFunction() {
// Declare a local variable, available only in the function
// Since this variable uses the same name as the global one
// when this function is executing, this variable will override
// (hide) the other one.
var go= "local";
console.log(go); // The local one is used
}
// Now, we are outside the function and the local version of "go" is
// out of scope. It's gone and can't be accessed. But, the global version
// is still available
console.log(go); // The global one is used
Here's your second example:
// Again, we're replacing document.write with console.log
// Even though we're calling the "myFunction" function when the
// window is loaded, that function only sets a local variable
// that will be destroyed when the function ends. It never does
// anything with that variable.
window.onload = myFunction;
var go="global";
function myFunction() {
// This will be destroyed as soon as the function is done
// which is the line right after it gets declared!
var go="local";
}
// Again, the scope of this line of code is global and so the global value is used
console.log(go);