Skip to content

Instantly share code, notes, and snippets.

@vlasovskikh
Created July 23, 2011 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlasovskikh/1101352 to your computer and use it in GitHub Desktop.
Save vlasovskikh/1101352 to your computer and use it in GitHub Desktop.
Local vars in CoffeeScript are nonlocal sometimes
f = ->
x = 2
x = 1
> console.debug "x = #{ x }"
x = 1
> console.debug "f() = #{ f() }"
f() = 2
> console.debug "x = #{ x }"
x = 1
x = 1
f = ->
x = 2
> console.debug "x = #{ x }"
x = 1
> console.debug "f() = #{ f() }"
f() = 2
> console.debug "x = #{ x }"
x = 2
@autotelicum
Copy link

From Smooth CoffeeScript p 49... (or p 51... with solutions):

When looking up a variable inside a function, the outer environment is checked first, and only if the variable does not exist there is it created in the local environment.
...
So if the name of variable in an inner function exists in an outer environment then the variable is referring to the outer one, it is not a new definition. That is an expression like variable = 'something' may be a definition of a new variable or it may be an assignment to a previously defined variable. As a matter of style, when you are using top-level variables then it makes sense to introduce them at the top of a file with a default value.
...
The easiest way to deal with variables is to use unique names for variables throughout a file.
...
There is also a diagram and a handful of examples.

@vlasovskikh
Copy link
Author

@autotelicum Yep, I'm aware of the scoping rules in CoffeScript, but they are a little bit weird from a pythonista's perspective. Thanks for the pointer to your book!

@autotelicum
Copy link

Then this might be more relevant:
http://blog.ssokolow.com/archives/2011/05/07/a-python-programmers-first-impression-of-coffeescript/
If you are interested in the pro/contra of scoping: jashkenas/coffeescript#1121

@vlasovskikh
Copy link
Author

@autotelicum Thanks for these very relevant links! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment