5
array = [1,2,3,4]

for num in array
    //do something

What is the value of num in the context of the rest of the function? Does num get scoped to the loop?

2
  • What happened when you ran it? Commented May 30, 2012 at 6:10
  • You can try CoffeeScript stuff and see the compiled result here =D Commented May 30, 2012 at 7:28

1 Answer 1

17

No, num doesn't get scoped to the loop. As you can see in compiled JS (as @epidemian pointed out) it is current scope variable, so you can access it also in the rest of the function (e.g. rest of the current scope).

But be careful in case of defining function callback inside the loop:

array = [1, 2, 3]

for num in array
  setTimeout (() -> console.log num), 1

outputs

3
3
3

To capture current variable inside the callback, you should use do which simply calls the function:

for num in array
    do (num) ->
        setTimeout (() -> console.log num), 1
Sign up to request clarification or add additional context in comments.

2 Comments

I've created some delightful race conditions with this mistake, be weary
Just got bit by this, too. I feel like do (num) -> should be the default behaviour.

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.