I would like to find the easiest way to be sure about the scope of variables.
Seeing at next example (jsfiddle):
var foo = function() {
var bar = function() {
pub = "public";
var pri = "private";
alert(pub) // public
alert(pri) // private
};
// alert(pub) // pub not defined
bar();
alert(pub) // public
// alert(pri) // pri not defined
};
foo();
alert(pub) // public
// alert(pri) // pri not defined
Can I say that:
1.- All variable prefixed with var keyword will be visible inside its function and all their nested function?
2.- All variable without var keyword will be visible everywhere after (his function container) be executed?
Since people mentioned globals…
You shouldn’t use globals, always declare your variables with var to avoid confusion. If you must use them, scope them to a global namespace that is used for your code. This will help you avoid collisions with other code on the page.