Variable scope in coffeescript for loop?

coffeescript

Solution

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

Problem

``` 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?

Original source