Wednesday 13 April 2016

Another Form of Ternary Operator In AngularJS

Once I was working on an AngularJS application. I have a requirement that under ng-repeat I need one object value with comma separated but ‘.’ in last. We can achieve this with the help of ternary operator very easily, but I found something different. This is like 

{{ !$last && ', ' || '.'}}


The above solution resolved the problem also, but the interesting thing is that who it is working. It creates a confusion in my mind. Now I started to find out the best answer for this. In-order to this I created a question on stackoverflow and got many answers all are same. Every explain that it is working as a Ternary operator. 

The best answer that I found is as given below.


It is a form of ternary operator. && returns first operand if it is a falsy value and second operand if first operand is truthy e.g. 1 && 3 will return 3 but 0 && 3 will return 0. Second operator is not evaluated if first is falsy. || is similar but returns first operand if it is truthy and second operand if first is falsy.


So basically cond && val1 || val2 is equivalend to cond ? val1 : val2 under condition that val1 is truthy value. If this is not the case e.g. cond && 0 || 1 this will always return last value 1 in this case.
For readability reasons you should always prefer ternary operator ?: than Boolean shortcircuting operators.

1 comment:

for ict 99 said...
This comment has been removed by a blog administrator.