For many people, javascript isn't their first programming language. Most of those people programmed in C++, Java or any number of other language which have block scoping. Javascript doesn't have block scoping, providing only global and function scopes (although you may nest function, each of which create their own scope.)
Thus is the code
if (true) {
var i=1;
}
alert(i);
will alert 1 by design (it isn't a bug.) The question becomes what happens if the conditional isn't true, so the block that defines i isn't executed?
if (false) {
var i=1;
}
alert(i); // alert shows undefined
alert(j); // throws "not defined" error as variable j is undeclared
In this case i exists, but it's value is undefined. And the variable j doesn't exist so it will throw an error that it isn't defined.
If this is new to you I recommend that you read section 4.3 on variable scope in Javascript: The definitive guide.
Many C++ programmers who use one letter variables are used to doing:
int i=1;
for (int i=0; i < foo.length(); i++) {
foo[i].bar(); // [1] here i refers to block scope of for statement
}
i = 0; // [2] here i refers to i defined on first line (eg i==1)
Whereas in javascript after running the for loop, i would be equal to foo.length() in statement [2].
Responses to "Javascript Scoping"
Leave a response