6 ms·
Blocks in JavaScript do not create scopes. This is different from many other languages (like Java or C). In fact, Crockford has mentioned this as well: http://
by jaysoo 16y ago
Blocks in JavaScript do not create scopes. This is different from many other languages (like Java or C).
In fact, Crockford has mentioned this as well: http://javascript.crockford.com/code.html 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.
- webuiarchitect 16y agoThat'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.
- jaysoo 16y agoNo problem. It's one of those things developers don't realize when coming from C-style languages. :)