Usman Sabuwala
Usman Writes


Usman Writes

The Ternary Operator

The Ternary Operator

Usman Sabuwala's photo
Usman Sabuwala
ยทAug 22, 2020ยท

2 min read

Play this article


This Blog Post is about the Ternary Operator in JS, C++, C, C#, Java, etc.

So, if you don't know, my name is Usman and I am a learner. Now let's start!

๐Ÿšจ A Ternary Operator is an operator that makes a decision based on what condition you pass in. It is simply an if else. But shorter

The Syntax is something like this:

CONDITION ? result_if_true : result_if_false

The process is as follows:

  1. You define your condition like name === 'Usman' or something else just like you pass inside of if.
  2. If the condition you passed in is true or correct, result_if_true will be returned.
  3. If it is false or incorrect, result_if_false will be returned.


var company = "Google";
if (company === "Google") 
    console.log("READY TO WORK!");
  console.log("I WILL ONLY WORK AT GOOGLE.");

๐Ÿ‘† This is the standard if else. You can transform this into a one-liner code.

As I told that result_if_true or result_if_false will be returned, so we will have to store the ternary expression in a variable or in a console.log().

So here, the CONDITION is company === "Google" and if it is true, we should return "READY TO WORK!", else we should return "I WILL ONLY WORK AT GOOGLE.".

So the code will be:

// CONDITION ? result_if_true : result_if_false
  company === "Google" ? "READY TO WORK!" : "I WILL ONLY WORK AT GOOGLE."


var myDecision = company === "Google" ? "READY TO WORK!" : "I WILL ONLY WORK AT GOOGLE.";

If the company is set to "Google", we will get the output "READY TO WORK!". Else, we will get "I WILL ONLY WORK AT GOOGLE.".

I hope you understood the Ternary Operator clearly. If yes, then it would be nice if you solve this simple CHALLENGE.

I also have a video on my channel about the Ternary Operator

If you have any suggestions or feedback. Please let me know in the comments. Happy Coding!

Share this