Global Scope
Take this example:
var a = 42;
var b = 57;
function example() {
var a = b = 10;
}
console.log(A = " + a, "B = " + b"; -> A = 42 B = 57
example();
console.log(A = " + a, "B = " + b"; -> A = 42 B = 10
Why?
This function could be re-written as:
//How the javascript compiler sees it:
function example_clear() {
var a = 10;
b = 10;
}
//When we don't have the 'var' keyword next to 'b', it is going to accessing the 'b'
//variable in the scope above it, which is the global scope.
When you don't use 'var' you are attaching it to the global object.
If you're in a function then var will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):