Someth Victory

Ruby, Rails, and Javascript Developer

There Is No Ternary Syntax in CoffeeScript

Ternary operator in CoffeeScript is not behaving as you expected. There is no error, but your application will behave with unexpected behavior.

See example below:

Example 1
1
hasName = name ? false : true

The hasName variable should return false or true base on whether or not variable name exist. And yes, it is like that in pure Javascript. But in coffeescript, when writing the code like this, the hasName variable will get the value of whatever the name variable is. If the name variable stores value of ‘Victory’, then the hasName will got the value of ‘Victory’ too, which will lead your application to behave strange in some case.

Fortunately, CoffeeScript has a very nice one line syntax which behaves exactly like ternary operator in pure Javascript.

Example 2
1
hasName = if name then true else false

Now, hasName variable will return false or true base on whether or not the name variable has value.