Variable scope in coffeescript for loop?

array = [1,2,3,4]

for num in array
    //do something

What is the meaning numin the context of the rest of the function? numgets into the loop?

+5
source share
1 answer

No, it numdoesn’t fall into the loop. As you can see in compiled JS (as @epidemian noted), this is the current variable of the sphere, so you can access it also in the rest of the function (for example, in the rest of the current area).

But be careful when defining a function callback inside a loop:

array = [1, 2, 3]

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

exits

3
3
3

To capture the current variable inside the callback, you should use dothat just calls the function:

for num in array
    do (num) ->
        setTimeout (() -> console.log num), 1
+17
source

All Articles