I watched this: http://www.youtube.com/watch?v=mHtdZgou0qU yesterday, and I've been thinking about how to improve my javascript. I'm trying to keep everything he said in mind when re-writing an animation that looked really choppy in firefox.
One of the things I'm wondering is if for
loops add on to the scope chain. Zakas talked a lot about how closures add on to the scope chain, and accessing variables outside of the local scope tends to take longer. With a for
loop, since you can declare a variable in the first statement, does this mean that it's adding another scope to the chain? I would assume not, because Zakas also said there is NO difference between do-while
, while
, and for
loops, but it still seems like it would.
Part of the reason I ask is because I often see, in JS libraries, code like:
function foo(){
var x=window.bar,
i=0,
len=x.length;
for(;i<len;i++){
//
}
}
If for
loops did add another object onto the chain, then this would be very inefficient code, because all the operations inside the loop (assuming they use i
) would be accessing an out-of-scope variable.
Again, if I were asked to bet on it, I would say that they don't, but why then wouldn't the variables used be accessible outside of the loop?