That doesn't even make sense. The for-loop block doesn't create a new scope, so it's perfectly valid to refer to the variable `a`. Plus, even if you create a new scope, you can still refer to `a` due to closure.
That doesn't even make sense. The for-loop block doesn't create a new scope, so it's perfectly valid to refer to the variable `a`. Plus, even if you create a new scope, you can still refer to `a` due to closure.
For example, if you ran the code below in FireBug you'll get the same results (minor variance aside).
function foo() { var a = 0; for (var i=0, j=a; i<10000000; i++) { var x = j+i; } }
function bar() { var a = 0; for (var i=0; i<10000000; i++) { var x = a+i; } }
(function() { var start = new Date().getTime(), end; foo(); end = new Date().getTime(); console.log(end-start); })();
(function() { var start = new Date().getTime(), end; bar(); end = new Date().getTime(); console.log(end-start); })();
In your examples, just change the value of variable 'a' to 100 or 1000 and you will see the difference.
In fact, Crockford has mentioned this as well: http://javascript.crockford.com/code.html
"JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages."
Which is why this code works:
(function() {
for (var i=0; i<100; i++);
alert(i);
})();Notice the variable `i` is accessible from outside the for-loop.
Another thing, JavaScript 1.7 has introduced block level scopes.. you can achieve that by using the 'let' keyword instead of 'var' to declare a variable. Although most browsers don't support it yet.