Avraam Mavridis Avraam Mavridis - 3 months ago 13
CoffeeScript Question

Difference between ternary (question mark operator) in coffeescript and in javascript?

I have this line in my code:

de: (_.max(data, (product) -> product.prices.de )).price.de


I want firstly to check that the
product.prices
is defined, if it is defined return
product.prices.de
otherwise return 0.
In javascript I would write something like this:

angular.isDefined(product.prices) ? product.prices.de : 0


but when I am trying the same thing in coffeescript the coffeelinter is not accepting it. Any hints?
Is there difference between coffeescript and javascript in the use of query operator?

Edit:

I could write

de: (_.max(data, (product) -> product.prices?.de )).prices.de


but in that case if
product.prices
does not exists the function returns null and not 0

Answer

The ternary operator in CoffeeScript is simply an if condition since everything in CoffeeScript is an expression. So the following:

condition ? something : somethingElse

Becomes:

if condition then something else somethingElse

Note that in your case though you wouldn't write:

if product.prices then product.prices.de else 0

You probably want:

product.prices?.de or 0
Comments