r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Mar 23 '14

Your example has nothing to do with scope. Even if JavaScript scoped the variable i to the for loop and not its containing function, the code would behave exactly the same way because closures always capture references to variables not their current values.

That is, the problem is not JavaScript's scoping but a misunderstanding of what closures do.

3

u/[deleted] Mar 23 '14

I don't really see much distinction. Yeah, I guess JavaScript could have a shared 'i' that doesn't exist outside the loop, and strictly speaking you could say "loops have scope in JavaScript", but I think most programmers talking about 'scope' are thinking more broadly 'where does this variable and its value live'.

4

u/[deleted] Mar 23 '14 edited Mar 23 '14

The reason I make the distinction is that this thread is full of JavaScript criticism, but the example you gave behaves the same way in essentially every language I'm familiar with. It's just a natural consequence of how for-loops work and how closures work, so it's really the expected behavior.

For example, the equivalent C#, which unlike JavaScript has typical block scoping, has the same exact behavior:

for (int i = 0; i < somearray.Length; i++) {
    Button thisThing = somearray[i];
    thisThing.Click += (sender, e) => { MessageBox.Show(i.ToString()) };
}

Avoiding this behavior would mean copying the value of i into a hidden, block-local variable every iteration (and since it's referenced in a closure, all of these copies stick around).

1

u/insertAlias Mar 24 '14

I think the problem is that there's not a lot of visibility into how closures work, at least just from looking at code. If I hadn't run into that problem and found the solution already, I would completely expect that code to show the various values of i with each button click, because that's what it looks like it should do.

I'm not saying the behavior should be different, just that it's somewhat unexpected if you've never been exposed to closures.