Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declaration in CoffeeScript

I notice that in CoffeeScript, if I define a function using:

a = (c) -> c=1 

I can only get the function expression:

var a; a = function(c) {     return c = 1; }; 

But, personally I often use function declaration,for example:

function a(c) {     return c = 1; } 

I do use the first form, but I'm wondering if there is a way in CoffeeScript generating a function declaration. If there is no such way, I would like to know why CoffeeScript avoid doing this. I don't think JSLint would holler an error for declaration, as long as the function is declared at the top of the scope.

like image 405
Grace Shao Avatar asked Jul 01 '11 13:07

Grace Shao


People also ask

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

Is CoffeeScript better than JavaScript?

"Easy to read", "Faster to write" and "Syntactic sugar" are the key factors why developers consider CoffeeScript; whereas "Can be used on frontend/backend", "It's everywhere" and "Lots of great frameworks" are the primary reasons why JavaScript is favored.


2 Answers

CoffeeScript uses function declarations (aka "named functions") in just one place: class definitions. For instance,

class Foo 

compiles to

var Foo; Foo = (function() {   function Foo() {}   return Foo; })(); 

The reason CoffeeScript doesn't use function declarations elsewhere, according to the FAQ:

Blame Microsoft for this one. Originally every function that could have a sensible name retrieved for it was given one, but IE versions 8 and down have scoping issues where the named function is treated as both a declaration and an expression. See this for more information.

In short: Using function declarations carelessly can lead to inconsistencies between IE (pre-9) and other JS environments, so CoffeeScript eschews them.

like image 178
Trevor Burnham Avatar answered Sep 28 '22 05:09

Trevor Burnham


Yes you can:

hello()  `function hello() {` console.log 'hello' dothings() `}` 

You escape pure JS via the backtick `

Note that you can't indent on your function body.

Cheers

like image 28
Zaid Daghestani Avatar answered Sep 28 '22 04:09

Zaid Daghestani