4

Is there any way to declare a variable at "file" scope (which will be closured by CS), without initializing it? A contrived example:

init = ->
  counter = 0

inc = ->
  counter += 1

This won't work, because you need to declare "counter". Adding "counter = 0" to the top would make it work, but the "= 0" is unnecessary. (A more realistic example would involve something that accesses the DOM on page load - there's no way to correctly initialize it in "file" scope.)

3 Answers 3

14

You'll have to define it on the outer scope, as you mentioned.

counter = null
init = ->
  counter = 0
inc = ->
  counter += 1
Sign up to request clarification or add additional context in comments.

2 Comments

+1. Shorthands have been proposed, but jashkenas is a firm believer in the = null syntax.
I haven't seen that, but I guess the rationale is to keep the keyword count low.
4

If your functions where part of an object you could use @counter, like this:

obj = 
  init: ->
    @counter = 0
  inc: ->
    @counter += 1

Comments

0

You can say `var counter;` with backticks and that is passed literally through to the generated javascript.

When you have a problem like this, look at the generated javascript. It will be extremely clear that the variable scope is lexically limited to the function.

Looking at the generated javascript is often a good way to understand what the behavior of coffeescript constructs is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.