Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
JavaScript will declare any variables lacking a var declaration (even those contained in a
function or encapsulated functions) to be in the global scope instead of
the intended local scope. Have a look at the code below and notice that
without the use of var to declare
bar, the variable is actually defined
in the global scope and not the local scope, where it should be.
<!DOCTYPE html><html lang="en"><body><script>
var foo = function() {
var boo = function() {
bar = 2; /* no var used, so bar is placed in the global scope
at window.bar */
}();
}();
console.log(bar); // logs 2, because bar is in the global scope
// As opposed to...
var foo = function() {
var boo = function() {
var doo = 2;
}();
}();
console.log(doo); /* logs undefined, doo is in the boo function scope,
error occurs */
</script></body></html>