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?
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.
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.
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.
JavaScript variables have different scopes, they are: Global Scope. Local Scope. Block Scope.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With