Avraam Mavridis Avraam Mavridis - 1 year ago 171
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
is defined, if it is defined return
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?


I could write

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

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

Answer Source

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

condition ? something : somethingElse


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download