Ternary Operator

why we use Ternary Operator and why we should replace if and else there is a reason and when ?

Ternary operators are useful for when we want to do something in response to a small condition. For example, if we wanted to check whether a users age was over 18 and return a relevant message. We could do it like this:

let message;
if(age > 18) {
  message = "You are above 18"
} else {
  message = "You are not above 18"
}

Now that works just fine and there’s no issues with doing it that way but it’s a fair amount of code for a pretty small operation, let’s refactor this using a ternary operator instead:

let message = age > 18 ? "You are above 18" : "You are not above 18"

Now that’s a lot less code the achieve the same thing and looks a lot cleaner imo.

Where are ternary operator is less useful is if you have a longer condition and/or you want to do more than simply set a value, that’s when it would be preferable to use a more standard if/else block instead.

2 Likes