3

I've been playing with CoffeeScript, and I've used js2coffee to experiment. One thing I noticed was the way CoffeeScript handles variable initialization. This CoffeeScript:

string = 'word'

compiles to this JavaScript:

var string;
string = 'word';

What is the advantage of the var string; declaration? Why not

var string = 'word';

4
  • I don't think there's any benefit; what compiler did you use? Commented Feb 23, 2013 at 19:23
  • js2coffee just allows you to type in CoffeeScript and it dynamically compiles to JavaScript real time. Check it out. Commented Feb 23, 2013 at 19:24
  • try a different compiler. This one likely isn't optimising Commented Feb 23, 2013 at 19:25
  • Very nice tool, I'll surely toy with it Commented Feb 23, 2013 at 19:29

2 Answers 2

6

coffeescript compiles to jslint-conform javascript, and puts all variable declarations to the top of the current scope/function.

Sign up to request clarification or add additional context in comments.

Comments

3

The advantage, is that all variables used in a scope can be declared together at the top of the scope with var, then used/assigned later...

var myThing, myOtherThing;

myThing = "a good thing";

... etc ...

2 Comments

That's a description of exactly what the code looks like and does, but it's definitely not an "advantage". Can you please explain why doing this is preferable to on-the-fly declarations?
@sheac it is an advantage in terms of reviewing the code, so it makes it easy to see at the start of the scope, what variables are used within the scope. It can help you to spot duplication - where you might have used two or more variables for the same purpose, and also clearly shows to you which scope the variable used within belongs to.

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.