So you’re wondering what that “?” followed by “:” means in your code. Yep, that’s the ternary operator all right!

What’s that, you ask? Well, it’s just another way to write your “if” conditions!

What’s the point, you ask again? You can write a shorter version of an “if” which can be useful in certain situations (we’ll discuss this on the guide!)

Basic usage of the ternary operator

To understand the ternary operator, first, take this overly familiar code

if (condition) {
  executeIfTrue();
} else {
  executeIfFalse();
}

Is there a way to make it shorter?

Hmm, maybe something like this?

if (condition) executeIfTrue();
else executeIfFalse();

All I did here was remove the brackets, which you can do only if you only have one line of code after the condition.

But you know what? Today I’m feeling like writing extremely short code, so this is not enough. Let’s try something new:

condition ? executeIfTrue() : executeIfFalse();

Wow, a 5-line code turned into one. The code above is exactly the same as the other ones before by the way. Try to understand the logic behind it before reading on by yourself.

.
.
.

Did you get it? Let’s make it simpler to understand:

(if) condition (then) executeIfTrue() (else) executeIfFalse();
     condition   ?    executeIfTrue()   :    executeIfFalse();

How is it? Feel like your brain grew a bit? Good. Now try to complete the following exercise:


Exercise 1

What does the following code output?

10 > 15 ? console.log("Today's going to rain") : console.log("Today's going to be sunny");
Solution
“Today’s going to be sunny”

All right, so we got the basics down. Let’s get to the most common uses cases of the ternary operator.

Common use cases

JSX

Note: if you’re not familiar with JS frameworks/libraries such as React yet, I suggest you skip to the next section.

Let’s take the following code, using React as an example.

import React, { Component } from 'react';
...
render() {
  if (condition) {
      return <div>Hello</div>;
  } else {
      return <div>Goodbye</div>;
  }
}
...

Although this works, sometimes you want to have conditional rendering inside the JSX portion of the code – especially if your code isn’t as short as the example here.

While you can’t use ‘if’ inside JSX, you can use ternary operators, like so

import React, { Component } from 'react';
...
render() {
  return <div>{condition ? "Hello" : "Goodbye"}</div>;
}
...

All right, let’s move on to more general use cases of this operator.

Fast variable assignment

Take the following example:

let message;
if (someCondition) {
  message = "Got it";
} else {
  message = "Nope, RIP";
}

Isn’t it frustrating to keep repeating this snippet all the time? Well, ternary operators let you write this condition efficiently:

let message = someCondition ? "Got it" : "Nope, RIP";

Damn, that’s a lot shorter.

Fast conditional returns

Following the same logic, let’s move on to another example:

function someFunction() {
  if (someCondition) {
    return "Hey there";
  } else {
    return "Bye";
  }
}

This is something that developers tend to do a lot, but there’s a shorter and faster way to do this. Can you guess how to do it?

Remember, you want to take a moment to try and figure these things out by yourself. If you can’t, scroll back up and reread the post. This is how things stick in your head.

.
.
.

function someFunction() {
  return someCondition ? "Hey there" : "Bye";
}

Did you get it right? Perfect, let’s move on to the exercise.


Exercise 2

What does the following code output?

let condition = 50 > 100;
let message = condition ? "Got it" : "Nope, RIP";
console.log(message);
Solution
“Nope, RIP”

Let’s move on to a more advanced usage of this operator.

Multiple operations in the ternary operator

“But wait, Helder, how do you run more than one instruction?” – you ask

Exactly, how do you convert the following code:

if (condition) {
  executeThis();
  executeSomethingElse();
} else {
  executeThat();
  executeFunc2();
}

To use the ternary operator instead?

This is where things get a little different. You will replace the brackets {} with parenthesis (), and separate each instruction with a comma , .

Example:

condition ? (executeThis(), executeSomethingElse()) : (executeThat(), executeFunc2());

Note: Changes are highlighted in red

Got it? Let’s test you out then.


Exercise 3

What does the following code output?

let condition = 100 > 15;
condition
  ? (console.log("Hey there"), console.log("How are you?"))
  : console.log("Welcome");
Solution
“Hey there”
“How are you?”

Note: Dealing with assignments

Still on the topic of executing multiple operations, you should know that, when you’re doing assignments, the order of the instructions matters.

For example:

let message = true ? ("Hi", "Assign this") : "Not printed";

What is the value of “message” here? Well, it’s the last instruction that you wrote, so in this case, it’s “Assign this”

Chaining conditions

Now, what if we want to use else if with the ternary operator? What if we want to convert the code

function someFunction() {
  if (someCondition) {
    return "First value";
  } else if (anotherCondition) {
    return "Second value";
  } else if (yetAnotherCondition) {
    return "Third value";
  } else {
    return "None of the other values";
  }
}

to use the ternary operator? Well, this is how you do it:

function someFunction() {
  return someCondition ? "First value"
    : anotherCondition ? "Second value"
    : yetAnotherCondition ? "Third value"
    : "None of the other values";
}

This is good to know, but I wouldn’t recommend using this unless on a very specific situation, and the reason is that the verbose (using ‘if’) version is much more readable. However, this is is still good to know so you’re not staring blankly if something like this shows up.


Exercise 4

What does the following code output?

function someFunction() {
  return false ? "First value"
    : 15 > 10 ? "Second value"
    : true ? "Third value"
    : "None of the other values";
}
console.log(someFunction());
Solution
“Second value”

That’s it, folks. If you have any questions or comments on this, do please post them below, I’ll be replying as much as I can. In the meantime, you can also check out my newest post on fetching in JS.

Also, if you’ve enjoyed this article, don’t forget to share because that helps me a lot. Thank you!