The Ternary Operator

therealnrf

therealnrf

Posted on October 5, 2021

The Ternary Operator

This article is part of the first installment of a series I'm calling JavaScript You Must Know. The aim of this series is to go over various fundamentals of the JavaScript language that a developer must know/understand before moving forward with any of the modern JavaScript frameworks like React, Angular, and Vue. Learning these fundamentals in parallel with the frameworks would also be acceptable.

This first installment of the series focuses on syntax-related topics and is called JavaScript You Must Know -- Essential Syntax.


The ternary operator is simply a shorthand for an if...else statement. It is used very liberally by JavaScript developers (and developers of other languages that have this operator). These days it is especially common to see the ternary operator being used in React code.

Syntax

The ternary operator is the only operator in JavaScript that takes three operands. Its syntax may take some getting used to but it is actually quite straightforward. Let's take a look. Please note that the parentheses and the angle brackets are not part of the syntax; I'm just using them for readability.

(condition) ? <expression A> : <expression B>

  • condition: an expression that evaluates to a truthy or a falsey value
  • expression A: this expression is evaluated/executed if the condition is true
  • expression B: this expression is evaluated/executed if the condition is false

The equivalent if...else statement for the example above would be:

if (condition) {
  <expression A>
} else {
  <expression B>
}
Enter fullscreen mode Exit fullscreen mode

Let's consider a more realistic(-ish) example. Assume we need a function that takes the current temperature value as its argument and returns a string saying if it is hot outside or not. Using an if...else statement, one might code the function like this:

function tellMeIfItsHotOutside(outsideTempInCelsius) {
  if (outsideTempInCelsius > 30) {
    return "It is kinda hot";
  } else {
    return "Na, not really hot";
  }
}

console.log(tellMeIfItsHotOutside(25)); // output: "Na, not really hot"
console.log(tellMeIfItsHotOutside(31)); // output: "It is kinda hot"
Enter fullscreen mode Exit fullscreen mode

Now, if we use the ternary operator instead of the if...else statement inside the tellMeIfItsHotOutside() function, it would look like this:

function tellMeIfItsHotOutside(outsideTempInCelsius) {
  return (outsideTempInCelsius > 30) ? "It is kinda hot" : "Not really hot";
}

console.log(tellMeIfItsHotOutside(25)); // output: "Na, not really hot"
console.log(tellMeIfItsHotOutside(31)); // output: "It is kinda hot"
Enter fullscreen mode Exit fullscreen mode

Looking at the examples above, I'd say that both are equally readable but the ternary operator is much more concise.

Nested Ternary Operator

The ternary operator can also be nested. For example, if you have an if...else statement like this:

if (firstCondition) {
  <expression A>
} else if (secondCondition) {
  <expression B>
} else {
  <expression C>
}
Enter fullscreen mode Exit fullscreen mode

You can replace it using the ternary operator:

(firstCondition) ? <expression A> :
  ((secondCondition) ? <expression B> : <expression C>);
Enter fullscreen mode Exit fullscreen mode

We've basically just replaced <expression B> with another conditional statement that uses the ternary operator. The same can be done with <expression A> as well. Remember, <expression A> and <expression B> (considering the first ternary example) can be any valid JavaScript expressions. This includes arithmetic and logical expressions, function calls, and more ternary expressions.

Let's apply all of this to our outside temperature example and say that our tellMeIfItsHotOutside() function is a tad more specific and follows the following logic:

  • If the outside temperature is more than 40 degrees, return "Very hot; stay in"
  • If the outside temperature is between 30 and 40 degrees, return "Yeah, it is hot"
  • If the outside temperature is between 25 and 30 degrees, return "Kinda hot, but not too much"
  • If the outside temperature is 25 degrees or less, return "It's actually really nice out"

First, let's do the if...else version.

function tellMeIfItsHotOutside(outsideTempInCelsius) {
  if (outsideTempInCelsius > 40) {
    return "Very hot; stay in";
  } else if (outsideTempInCelsius > 30) {
    return "Yeah, it is hot";
  } else if (outsideTempInCelsius > 25) {
    return "Kinda hot, but not too much";
  } else {
    return "It's actually really nice out";
  }
}

console.log(tellMeIfItsHotOutside(41)); // output: Very hot, stay in
console.log(tellMeIfItsHotOutside(32)); // output: Yeah, it is hot
console.log(tellMeIfItsHotOutside(26)); // output: Kinda hot, but not too much
console.log(tellMeIfItsHotOutside(22)); // output: It's actually really nice out
Enter fullscreen mode Exit fullscreen mode

Now let's see what the same function would look like if we had used the ternary operator.

function tellMeIfItsHotOutside(outsideTempInCelsius) {
  return (
    (outsideTempInCelsius > 40) ? "Very hot; stay in" :
      (outsideTempInCelsius > 30) ? "Yeah, it is hot" :
        (outsideTempInCelsius > 25) ? "Kinda hot, but not too much" : "It's actually really nice out"
  );
}

console.log(tellMeIfItsHotOutside(41)); // output: Very hot, stay in
console.log(tellMeIfItsHotOutside(32)); // output: Yeah, it is hot
console.log(tellMeIfItsHotOutside(26)); // output: Kinda hot, but not too much
console.log(tellMeIfItsHotOutside(22)); // output: It's actually really nice out
Enter fullscreen mode Exit fullscreen mode

If you're not already used to the syntax of the ternary operator then I'd highly recommend doing this example on your own so the syntax sinks in nicely. Note that I've used indents and line breaks to make the syntax more readable. In my opinion the ternary version is much more readable in this case. Some of you may find the if...else version more readable. The important thing is to have code-readability as a priority. Always take some time to think which version will be easier to read and follow. Because that is the version that will be easier to debug, refactor, expand, and all that jazz.


👉🏻 Subscribe to my newsletter: click here

👉🏻 Follow me on twitter: click here


💖 💪 🙅 🚩
therealnrf
therealnrf

Posted on October 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related