Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about CoffeeScript variable scope

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?

like image 674
Sam Kong Avatar asked Mar 26 '12 01:03

Sam Kong


1 Answers

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:

a = 1
changeValue = lambda do
   a = 3
end
changeValue()

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!

like image 152
Blacksad Avatar answered Oct 22 '22 15:10

Blacksad