Hacker News new | past | comments | ask | show | jobs | submit login

I don't know Coffeescript - does it implicitly create a local var when there is already a global with the same name?



CoffeeScript doesn't allow you to shadow variables in enclosing scopes. The compiler will declare the variable in the "outer-most" scope in which is is used and then any uses in enclosed scopes refer to that one.

In this case as long as OP was not using the variable in an enclosing scope, it would have been made local to the function.


This is true for the most part, but there's a subtle edge case. Within a nested function, variables used in loops will redeclare within the inner function:

  ->
    outerVar = "outer"
    ->
      # this will output "undefined" 
      # as CoffeeScript has redeclared it for the loop:
      console.log outerVar 
      0 for outerVar in [0]


Huh -- that looks like a (new) bug to me. We should reuse the external declaration.


And CS also wraps modules in closures (by default), so an outermost-scoped variable is still local to the script, whereas it would be global to all scripts in vanilla JS.


It always creates a local var. You can only assign to globals indirectly, through properties of the global object e.g. window.foo = 123.


CoffeeScript is a compiler, so obviously it doesn't know anything about your runtime. It declares variables in the scope they're first assigned in; so 'global.x = y' works, while 'global = {}' compiles to 'var global; global = {};'.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: