Ternary Operators can clean up your code

JavaScript Syntax for ternary operators

(condition) ? true : false;

Use Case

Consider a situation where you need to work with 3 variables where the assignment of one variable depends upon comparing the other 2 variables.

var netWorthBill = 89;
var netWorthWarren = 80;
var highestNetWorth;

I could go about doing this with if else statements as shown below

if(netWorthBill > netWorthWarren){
highestNetWorth = netWorthBill;
}
else{
highestNetWorth = netWorthWarren;
}

OR

a better option would be to use this:

highestNetWorth = (netWorthBill > netWorthWarren) ? netWorthBill : netWorthWarren;

Used a ternary operator in an interesting way? Let us know in the comments

Interesting read on Ternary Operators

Author: Victor Fernandes

A friend I really respect once told me, unless you are able to dumb down a concept for someone who has no prior information about it, you can't be sure you know it yourself. I try to create blog posts that are extremely easy to understand most suitable for those in a hurry. The topics I write about include web development, digital marketing and software in general.

 
Notice an error in any content or would like to get something removed? Please inform Victor here.

Leave a Reply

Your email address will not be published. Required fields are marked *