Is a for loop adding another object to the scope chain in Javascript?

I watched this: yesterday and I was thinking about how to improve my javascript. I'm trying to keep everything he said in mind when rewriting an animation that looked really messy in firefox.

One of the things I'm curious about is that a loop is added to the scope chain for

. Zakas talked a lot about how closures are added to the visibility chain, and accessing variables outside the local scope tends to take longer. With a loop for

, since you can declare a variable in the first expression, does that mean it is adding another scope to the chain? I would guess not, because Zakas also said that there is no difference between loops do-while

, while

and for

, but it still seems like it will.

Partly I'm asking because I often see code like this in JS libraries:

function foo(){


If the loops for

added another object to the chain, it would be very inefficient code, because all operations inside the loop (provided that they use i

) will have access to an out-of-scope variable.

Again, if I'm asked to argue this, I would say they don't, but why then won't the variables be available outside of the loop?


source to share

1 answer

JavaScript is not block-scoped and has variable hoisting, so any variables that appear to be defined in the loop for

are not actually defined there.

The reason you see the code in your example is because of the hoisting behavior. The author of the code is aware of variable swapping, so he declared all the variables for scope at the beginning, so he clearly shows what JavaScript does.



All Articles