Javascript Ternary Operator for the win

Meet Pandya
2 min readAug 5, 2022

So, this title could have also said Typescript Ternary Operator as it is supported by both the programming languages.

Ternary Operator is a short-hand form to write a simple If/Else block.

The below example is a simple way of using the ternary operator which involves a ? and :

We have two integer variables & we are trying to decide if the speed is above the limit then return True or return False

With a ternary operator, everything that is before the ? is the conditional part. Whatever is between ? and : gets executed if the condition is true. If the condition is false, then whatever is after : gets executed

Below is what you would have of the previous code without using a Ternary Operator

Moral of the story is, Ternary Operator can make your basic If/Else blocks look a lot cleaner and simpler to read.

Don’t get into the habit of using Ternary in complex situations or nested Ternary

--

--