Question: In Javascript, if I declare variables with var in javascript outside of a function

```
var foo = 1;
var bar = 2;

function someFunction() {
    ....
}

```

are those variables within the scope of the document or the window? Furthermore, why does this matter? I know that if one declares a variable without var, then the variable is global.

Is there a simple way for me to test whether a variable falls within the scope of the document or the window?

Answer: 
When you declare a function in JavaScript, it creates a scope.

When you declare a variable, it must have a `var`. The `var` determines what scope it belongs and where it is visible. If it has no `var`, then it's an "assignment" to a variable and the browser assumes that a variable with that name exists in the outer scopes. 

When an assignment happens, the browser searches outwards until it reaches the global scope. If the browser does not see the assigned variable in the global scope, it will declare it in the global scope (which is not good)

for example, take the following as a demo of scope visibility and *not actual working functions*:

```
//global variables
var w = 20
var x = 10

function  foo(){
    function bar(){

        //we assign x. since it's not declared with var
        //the browser looks for x in the outer scopes
        x = 0;

        function baz(){

            //we can still see and edit x here, turning it from 0 to 1
            x = 1;

            //redeclaring a variable makes it a local variable
            //it does not affect the variable of the same name outside
            //therefore within baz, w is 13 but outside, it's still 20
            var w = 13;

            //declaring y inside here, it does not exist in the outer scopes
            //therefore y only exists in baz
            var y = 2;

            //failing to use var makes the browser look for the variable outside
            //if there is none, the browser declares it as a global                
            z = 3;
        }
    }
}

//w = 20         - since the w inside was "redeclared" inside 
//x = 1          - changed since all x operations were assigments
//y = undefined  - never existed in the outside 
//z = 3          - was turned into a global

```
as JavaScript has only function scope, variables defined by the `var` keyword are scoped to the containing function.

you can easily check for global scoping by opening the JavaScript console in the browser (or directly in your code), and typing:

```
varRef && console.log(varRef)

```