Ternary operator in javascript

Ternary operator is used like conditional operator, It evaluates a Boolean expression and returns the result based on its boolean expression.

Syntax:

condition ? consequent : alternative

We can use consequent again as ternary operator. The condition expression must return either true or false value. If condition evaluates to true, the consequent expression will be result of the operation.

If condition evaluates to false, the alternative expression evaluation will be the result of the operation. The type of consequent and alternative evaluation must be same.

Lets find greatest among two numbers. we can achieve it by simply if else statement as follows.

var a = 12, b = 23; var c; if(a>b) c=a; else c=b; document.write('Greater number is:'+ c);

OUTPUT:
Greater number is:23

Using ternary operator

var a = 12, b = 23; var c ; c = (a>b) ? a : b; document.write('Greater number is:'+c);

OUTPUT: Greater number is:23

What we will do for three numbers comparison instead of two numbers/p> var a = 105, b = 19, c=17; var d; if(a>b){   if(a>c)       d=a;   else       d=c;   } else{   if(b>c)       d=b;   else       d=c;   } document.write('Greatest among three numbers is:'+d);

OUTPUT: Greatest among three numbers is:105

Using Nested Ternary operator

var a = 105, b = 19, c=17; var d;   d = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b: c); document.write('Greatest among three numbers is:'+d);

OUTPUT: Greatest among three numbers is:105

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories