Skip to content

Instantly share code, notes, and snippets.

@zeppelin
Created August 21, 2011 09:07
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 zeppelin/1160370 to your computer and use it in GitHub Desktop.
Save zeppelin/1160370 to your computer and use it in GitHub Desktop.
foo = 10
bar = ->
((foo)->
foo = 20
console.log foo # => 20
)()
console.log foo # => 10
foo = 30
bar()
console.log foo # => 30
@TrevorBurnham
Copy link

You could use the do keyword rather than wrapping your function in parentheses:

foo = 10

bar = ->
  do (foo) -> 
    foo = 20
    console.log foo # => 20
  console.log foo # => 10

  foo = 30

bar()
console.log foo # => 30

But generally speaking, the use of shadowing is discouraged in CoffeeScript. There's been talk of adding a compiler warning in cases like this where a function argument shadows a variable declared in a surrounding scope. The exception is that shadowing is highly useful in a loop, which is why the do keyword was added to the language:

for i in [1..3]
  do (i) ->
    setTimeout (-> console.log i), 1 # 1, 2, 3

(Without the do, you'd get 4, 4, 4, since the function passed to setTimeout is only invoked after the loop has completed.)

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