Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope in coffeescript for loop?

Tags:

coffeescript

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?

like image 565
fancy Avatar asked May 30 '12 06:05

fancy


People also ask

What is the scope of a variable in a for loop?

In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

What is variable scope?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified. In the next section, you'll learn about local scope of variables.

What are the valid scoped of a variable in JavaScript?

JavaScript variables have different scopes, they are: Global Scope. Local Scope. Block Scope.


1 Answers

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
like image 84
zbynour Avatar answered Jan 03 '23 17:01

zbynour