var name = prompt(“Enter your name”, “Name”);
document.write(“<H2> Hello ” + name + “</H2>”);
In this example name is defined as global and accessed through different portion of the page.Now let us understand how it is saved inside the memory. when it is running it takes the input from user and stores that inside of “name” variable. This is outside of any function hence it is placed inside the global scope. Now when we require the “name” it check the scope. It is not inside of any function or block so it then goes for the global scope. If found inside global scope, the reference is established.
Let us take a second example
For further reference: