Re:Advanced JavaScript Techniques
by ramen on Friday October 09, 2009 @03:02PM
(#872202)
For-loops like "for (i=0;i<myLinkCollection.length;i++)" should always be written like "for (var i=..."), unless there's an explicit "var i;" declaration somewhere. Otherwise, this creates a global variable "i", which can lead to some very confusing bugs if another function is called that also references the global "i".
[ Parent
| on HN ]
But don't make the mistake of assuming that when writing "for (var i=...)" that i is scoped to the loop block. JavaScript does not have block scope. It only has function scope, with the "Global Object" scope being the top level scope.
Only with JS <1.7. Otherwise you get block scope by using 'let instead of 'var.
Only SpiderMonkey (Gecko) has that. And it will remain that way for the foreseeable future.
You'll get better performance with
for (var i=0, l=myLinkCollection.length; i<l; i++) { }
http://robertnyman.com/2008/04/11/javascript-loop-performanc...
Re:Advanced JavaScript Techniques
by WalkingDead on Saturday October 10, 2009 @04:05AM
(#873108)
Probably first time I am seeing a micro-optimization having some really significant impact on a micro-benchmark test.