Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript do, pass argument

The following CoffeeScript code:

do (a) ->
    console.log a

generates this:

(function(a) {
  return console.log(a);
})(a);

How do I pass a value to a like this?

(function(a) {
  return console.log(a);
})("hello");
like image 861
chenglou Avatar asked Aug 08 '12 16:08

chenglou


People also ask

What is the point of CoffeeScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

Why should you use CoffeeScript instead of JavaScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.

What does CoffeeScript compile to?

CoffeeScript. CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart.


1 Answers

do (a = 'hello') ->
  console.log a

Will generate exactly what you want.

Though, i have to admit that i can't see the point of doing that. If you really want a to take the literal value 'hello' inside that scope, then why make another scope? With a being a normal variable declared as a = 'hello' will be enough. Now, if you want to replace a with the value of another variable (that might change in a loop or something) and do do (a = b) -> then i think it makes more sense, but you could simple do do (a) -> and just use a instead of b inside the do scope.

like image 169
epidemian Avatar answered Oct 14 '22 07:10

epidemian