Use JavaScript Ternary Operator as an Alternative for If/Else Statements

Article By Digamber Rawat on

JavaScript Ternary Operator

Ternary operator JavaScript is what you use to shorten your if statements in your code segment. Ternary operator JavaScript is capable of turning a full-fledged if statement into a single line of code.

The ternary operator JavaScript will assign a value to a variable if it satisfies a certain condition. Interestingly, it is the only operator that accepts 3 operands.

You are already familiar with the if statement. You assign a certain value to the variable if it satisfies a condition; else you assign a different value to the same variable. The ternary operator JavaScript is an alternative option here.

Let’s have a look at a regular if statement below.

if (condition) {
  //  if the condition is true this block of code will be executed 
} else { 
  //  if the condition is false then this block of code will be executed
}

#Example 2

if (time < 12) {
  greeting = "Good Day";
} else if (time < 20) {
  greeting = "Good Day";
} else {
  greeting = "Good Evening";
}

Now let’s find out the ternary operator JavaScript version of the same if statement. What we are going to have is a single statement below.

let result = (condition) ? ‘value if true: ‘value if false;

Even though it is self-explanatory, we will explain it to you. When the condition is true the JavaScript ternary operator will return the value of the first expression; otherwise, it will return the value of the 2nd expression.

Let’s have a detailed look below.

First, we will come up with a variable where you store the value. We have chosen ‘result’ as a variable here. Output variable takes different values as per the conditions.

Pay attention to the fact that condition is placed on the right-hand side.
As you can see, there is a question mark (?) right after condition. It simply stands for “was this condition true?”

The possible outputs are followed. You will find a colon (:) in the middle, separating them.

However, you will be able to use the ternary operator example JavaScript this way only in the case of an if statement in the above format. However, this format is very well known. Hence you can use a ternary operator to your advantage in an efficient manner.

JavaScript Ternary Operator Example

It’s time for us to look at an example of a ternary operator.

Here in this example, we are going to find out the legal age for driving vehicles.

Let’s dive right into the conditional statement below:

let age = 19;
let eligibile_for_driving;

if (age > 18) {
   eligibile_for_driving = 'Eligible';
}
else {
   eligibile_for_driving = 'Not Eligible';
} 

console.log(eligibile_for_driving)
// Result: Eligible

Let’s rewrite the if statement with the ternary operator below:

let age = 19;

let eligibile_for_driving = (age < 18) ? "Not Eligible" : "Eligible";

// Result: Eligible

In this example, it will clearly return “Eligible” since we have chosen 19 as the value for legal age for driving a vehicle.

In this example, it will return “Eligible” since we have chosen 19 as the value for legal age for driving a vehicle.

Javascript Ternary Operator with Multiple Statements

Let’s take a look at an example involving multiple evaluations next:

var name = true;
var age = true;
var message = '';

if (name){
  if(age){
    message = "Whats your name and age"
  }else{
    message = "Your name is cool"
  }
} else {
  "What should i call you then"
}

console.log(message)

setting up multiple statements with ternary operator is very easy.

var name = true;
var age = true;

var message = name? (age ? "Whats your name and age" : "Your name is cool") : "What should i call you then"

console.log(message)

Ternary Operator JavaScript Implications

There are things you need to keep in mind when it comes to using the ternary operator. For instance, the ternary operator is not best known for its readability. We all have been used to “IF-ELSE”, and it becomes easier for us to read the code in this case.

Whenever you use the ternary operator or any other abbreviated code, you need to keep in mind who is going to read the code later on. If developers who are inexperienced are going to look at the code later on when it is better to avoid ternary operator for their sake, this holds especially true in case if you use complex conditions and evaluations. Alternatively, when you have to opt for a chain or nest ternary operator. Yes, nested ternary operator not only makes it difficult to read but also prone to debugging errors.

So, one has to consider usability and context before using a ternary operator as it happens with any other programming decision.

Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me