Programmers used to Java would often assume that block scope in JavaScript behave the same way, but they don’t. Most programmers know that JavaScript has global scope and function scope and that you need to declare variables with “var” within functions in order to make the variables local.
function scope1() {
test = "ok"; //global scope (without var)
}
scope1();
alert(test); //displays "ok"
function scope2() {
var test = "ok"; //local scope (with var)
}
scope2();
alert(test); //displays "undefined" since we are trying to display a global var
Now comes the “no block scope” in JavaScript – variables are all at function scope no matter where the variable is declared within the function. Even when within a try catch clause, for example.
function scope3() {
try {
var test = "ok"; // variable declared inside try catch is still function scope
} catch(err) {
}
alert(test); // displays "ok" since we are still inside function
}
scope3();
Or in a for loop.
function scope4() {
for(var i=0; i<10; i++) {
}
alert(i); //displays "10", variable i is available outside of for loop!
}
scope4();
The catch exception object, however, is still only available within its own scope – same as Java.
function scope5() {
try {
throw new exception("fake error");
} catch(err) {
// err is only available within this block
var test = "ok";
}
alert(test); // displays "ok", still function scope
alert(err); // displays "undefined", err is only available within catch clause
}