I am trying to understand how CoffeeScript variables are scoped.
According to the documentation:
This behavior is effectively identical to Ruby’s scope for local
variables.
However, I found out that it works differently.
In CoffeeScript
a = 1
changeValue = -> a = 3
changeValue()
console.log "a: #{a}" #This displays 3
In Ruby
a = 1
def f
a = 3
end
puts a #This displays 1
Can somebody explain it, please?
Ruby’s local variables (starting with [a-z_]) are really local to the block they are declared in. So the Ruby behavior you posted is normal.
In your Coffee example, you have a closure referencing a. It’s not a function declaration.
In your Ruby example, you don’t have a closure but a function declaration. This is different. The Ruby equivalent to your Coffee is:
In closures, local variables present when the block is declared are still accessible when the block is executed. This is (one of the) powers of closures!