Pergunta

This CoffeeScript:

x = y > z ? 'a' : 'b'

Compiles to:

x = (_ref = y > z) != null ? _ref : {
  'a': 'b'
};

I assume this is expected, just not intuitive.

This there a better way to do this in coffeescript?

Foi útil?

Solução

CoffeeScript's ? operator is the existence operator ("soak" or "elvis" names are also used). exemple : context = window ? global.

The CoffeeScript way of doing it is x = if x > z then 'a' else 'b' (or x = x > z and 'a' or 'b', but the "and" operand must be truthy for this to work) which will compile down to the ternary operator you'd expect.

Outras dicas

You can use if instead of ?::

x = if y > z then 'a' else 'b'

this compiles to

var x;

x = y > z ? 'a' : 'b';

I guess this is what I want, but I don't know if I happy with it.

Coffeescript:

x = if y > z then 'a' else 'b'

Javascript

x = y > z ? 'a' : 'b';
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top