3

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?

mowwwalker
  • 16,634
  • 25
  • 104
  • 157

1 Answers1

5

JavaScript does not have block scope and it has variable hoisting, so any variables that appear to be defined in a for loop are not actually defined there.

The reason you see code like provided in your example is because of the hoisting behaviour. The code's author knows about variable hoisting so has declared all the variables for the scope at the start, so it's clear what JavaScript is doing.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Alright, that's what I assumed after seeing: http://stackoverflow.com/questions/1236206/one-var-per-function-in-javascript, but why then are the variables not accessible outside of the loop? – mowwwalker Mar 20 '12 at 21:39
  • Although personally I think it's confusing to put the loop's initialiser in the `var`... I always do `var i;` but keep the `i=0` in the `for(...)`... – Niet the Dark Absol Mar 20 '12 at 21:39
  • 1
    @Walkerneo Any variables that appear to be defined inside of a loop *are* accessible outside the loop. – alex Mar 20 '12 at 21:45
  • @alex, Wow, I really had no idea you could do that. Thanks! – mowwwalker Mar 20 '12 at 21:47