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?

1
  • Variables declared inside for loops get hoisted anyway, so there's no reason to explicitly declare them up front. Commented Mar 20, 2012 at 21:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Alright, that's what I assumed after seeing: stackoverflow.com/questions/1236206/…, but why then are the variables not accessible outside of the loop?
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(...)...
@Walkerneo Any variables that appear to be defined inside of a loop are accessible outside the loop.
@alex, Wow, I really had no idea you could do that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.