Helder Esteves

Type and hit Enter to search

JavaScript
Uncategorized
Software Architecture
React
General
Management
Next.JS
TypeScript
JavaScript
Uncategorized
Software Architecture
React
General
Management
Next.JS
TypeScript
JavaScript

Ternary Operator in JavaScript: The Complete Guide

Helder Esteves
Helder Esteves
February 10, 2023 4 Mins Read
73 Views
0 Comments

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!)

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();

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 bold

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 in 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”


Conclusion

That’s it, folks. If you have any questions or comments here then please post them below, I’ll be replying as much as I can!

Tags:

Beginner

Share Article

Other Articles

Next

Fetching in JavaScript: The Definitive Guide

Next
February 15, 2023

Fetching in JavaScript: The Definitive Guide

No Comment! Be the first one.

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Subscribe
    Stay Updated!
    Get notified when awesome content is posted. Learn more everyday.
    Most Read
    Software Architecture
    5 JS Design Patterns Every Developer Should Know
    March 10, 2023
    5 Min Read
    yellow line on gray asphalt road
    Next.JS
    5 Next.JS Tips You Never Heard About
    March 27, 2023
    4 Min Read
    blue UTP cord
    Uncategorized
    Setting up a TURN server with Node: Production-ready
    May 19, 2023
    5 Min Read
    Most Engagement
    brown rope on black background
    Uncategorized
    The Crash Course on Node Redis

    Learn everything you need to know for Node Redis! The only article you'll need to read, from...

    March 3, 2023
    4 Min Read
    Most Recent
    grayscale photo of person holding glass
    JavaScript
    Top 10 JavaScript Coding Challenges You Must Absolutely Know
    May 17, 2023
    9 Min Read
    a person pointing at a rock with writing on it
    JavaScript
    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    5 Min Read
    blue UTP cord
    Uncategorized
    Setting up a TURN server with Node: Production-ready
    May 19, 2023
    5 Min Read

    Related Posts

    JavaScript
    Simple Backgrounds For Websites — Cheat Sheet
    February 21, 2023
    3 Min Read
    Read More
    person showing thumb
    Software Architecture
    Premature Optimization: A Software Developer’s Worst Nightmare
    April 24, 2023
    3 Min Read
    Read More
    a person pointing at a rock with writing on it
    JavaScript
    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    5 Min Read
    Read More
    JavaScript
    Generating Random Colors in JS + Dark, Light colors
    February 18, 2023
    4 Min Read
    Read More

    Helder Esteves

    Read everything there is to know about the JavaScript development ecosystem, from programming to project management.

    Recent

    7 Best Coding Challenge Websites for 2023: Improve Your Skills and Boost Your Career
    May 20, 2023
    Setting up a TURN server with Node: Production-ready
    May 19, 2023

    Categories

    JavaScript9
    Uncategorized4
    Software Architecture2
    React2

    Contact

    Reach out to us through helder.writer@gmail.com

    © 2022, All Rights Reserved.

    Go to mobile version