Ternary Operators can clean up your code

By October 27, 2017 July 21st, 2019 No Comments

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;
  highestNetWorth = netWorthWarren;


a better option would be to use this:

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

Interesting read on Ternary Operators

Victor Fernandes

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.

Leave a Reply

Contact Me

If you prefer email, you may also email me at [email protected]