In the case of closure, yes you will take a small performance hit. But the example given is still invalid because the only scope present is the function-scope (for-loop doesn't create new scope).
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);
})();
That's correct. Thanks a lot. Updated the blog with the correct example (using function). I was testing on Chrome and even your examples showed better results with value of variable 'a' to 1000, although slightly. Firefox shows no difference.
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.
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); })();