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