Coffee Script: si .. es .. entonces

I'm writing a rock paper scissor game with Coffee Script and the code is not compiling as I'd expect.


if choice is opponent_choice then alert "Tie!"

Compila a

if (choice === opponent_choice) alert("Tie!");

But I was expecting

if (choice === opponent_choice) {

What do I need to change for this to compile in the way I expected?

preguntado el 09 de marzo de 12 a las 23:03

Those two bits of code are equivalent. Why do you specifically need the latter and not the former? -

Why use coffee script as the source. If you want that much close control on the compiled javascript, why not just write javascript? -

4 Respuestas

If there's only one statement on a line, you don't need the braces. They are functionally identical, and coffeescript compiler optimizing the output to use the least amount of characters.

respondido 09 mar '12, 23:03

¿Por qué eso importa?

For CS to create a block/multi-line then you need to actually have a multi-line then, me gusta:

if choice is opponent_choice
  alert "Tie!"
  alert "Foo"

Que se compila para:

if (choice === opponent_choice) {

respondido 09 mar '12, 23:03

Change your expectation, not the output.

Edit: add some details

CoffeeScript is a fine tool, not only a shorter way of writing code (which it is), but it re-formats many common patterns into good javascript. The output is often less readable than what you might have written yourself in javascript, but what it loses in clarity, it gains in improved programming patterns.

You should treat the CoffeeScript as the source, and not the compiled output. You would not dream of editing compiled output from other languages would you? (I know the analogy is a little bit of a stretch - but the point remains, source is for reading/writing and compiled output for executing).

respondido 10 mar '12, 00:03

// Generated by CoffeeScript 1.7.1

I use coffee of this version and can compile in the way you expected.

(function() {
  if (choice === opponent_choice) {


You can have a try. However, I recommend you not to pay too much attention to the compiled output. It doesn't matter.

Respondido el 14 de Septiembre de 14 a las 10:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.