Clean code with the Ternary Operator

You will discover in this article how to use the JavaScript ternary operator to streamline your code.

An introduction to the ternary operator in JavaScript

An if…else statement is frequently used to determine whether to run a block of code if a condition evaluates to true. For instance:

let varAge = 36;
let varMessage;

if ( varAge >= 18) {
  varMessage = 'You qualify to have a national identity card.';
} else {
  varMessage = 'You do not qualify to have a national identity card.';
}

console.log(varMessage);

In this illustration, we demonstrate the message that a person can have a national identity card if the person’s age is at least 18 years old. As an alternative, you can use the following ternary operator in place of the if-else statement:

let varAge = 36;
let varMessage;

varAge >= 18 ? ( varMessage = 'You can have a national identity card.') : ( varMessage = 'You cannot have a national identity card.');

console.log(varMessage);

Alternatively, you might make the following expression with the ternary operator:

let varAge = 36;
let varMessage;

varMessage = varAge >= 18 ? 'You can have a national identity card .': 'You cannot have a national identity card.';

console.log(varMessage);

The ternary operator’s syntax is as follows:

condition? expressionIfTrue : expressionIfFalse;

The condition in this syntax is an expression that yields a true or false Boolean value. The first expression (expresionIfTrue) runs if the condition is true. On the other hand, expressionIfFalse, the second expression, gets executed if it is false. The ternary operator’s syntax, as used in an expression, is demonstrated by the following:

let variableName = condition ? expressionIfTrue : expressionIfFalse;

In this syntax, the variableName will accept the first expression’s result if the condition is true or expressionIfFalse if it is false.

Illustrating Ternary operator using Developer Stage

It is assumed that you should be familiar with the if-else statement in any programming language. As a result, if-else simply runs our code based on a condition. If the status of the condition is true, the if block will run; otherwise, the else block will run. The sample example for the if-else block is shown below.

var yearsOfExperience = 5;
var position;
 if( yearsOfExperience > 4){
     position = "Senior Software Developer";
 }else{
     position = "Junior Software Developer";
 }

As presented in the code excerpt above, we utilized an if-else expression, which lengthens our code. However, the question of how to shorten it and how to optimize it now arises.

In this situation, Javascript’s ternary operator plays a key role. When we substitute the ternary operator for the if-else statement, our code is both shorter and cleaner-looking than when we use the if else statement.

Before examining how the ternary operator might be used to improve the above code, let’s first learn a sample ternary operator syntax in Javascript.

One of the key ideas to keep in mind is that the ternary operator in Javascript is the sole operator that accepts all three operands. Let’s now examine how the ternary operator can optimize the code for the if-else sentence we previously examined. The if-else statement example with the ternary operator in Javascript has been optimized and is shown below.

position = yearsOfExperience > 4 ? "Senior Software Developer" : "Junior Software Developer";

A sample example of how to do this is shown below. We can also combine many ternary operators into a single sentence.

position = yearsOfExperience > 5 ? "Principal Software Developer" : ( yearsOfExperience > 4 ?"Senior Software Developer" : "Junior Software Developer" );

The entire code for every example we covered in this section is provided below.

var yearsOfExperience = 4;
var position;
if( yearsOfExperience > 4){
  position = "Senior Software Developer";
}else{
  position = "Junior Software Developer";
}
console.log(position);

position = yearsOfExperience > 4 ? "Senior Software Developer" : "Junior Software Developer";
 yearsOfExperience = 2;
position = yearsOfExperience > 4 ? "Senior Software Developer" : "Junior Software Developer";
console.log(position);
 yearsOfExperience = 6;

 position = yearsOfExperience > 5 ? "Principal Software Developer" : ( yearsOfExperience > 3 ?"Senior Software Developer" : "Junior Software Developer" );
 console.log(position);

  yearsOfExperience = 2;
   position = yearsOfExperience > 5 ? "Principal Software Developer" : ( yearsOfExperience > 3 ?"Senior Software Developer" : "Junior Software Developer" );

  console.log(position);

JavaScript Nested Ternary Operator

Like if…else, ternary operators can also be nested to check many conditions. However, this makes the code harder to comprehend and is not advised. First, examine the if…else code that determines the leap year.

const varYear = new Date().getFullYear();
let isItALeapYear;
if ( varYear % 4 === 0) {
  if ( varYear % 100 === 0) {
    if ( varYear % 400===0) {
      isItALeapYear = "it is a leap year";
    }
    else {
      isItALeapYear = "it is not a leap year";
    }
  }
  else {
    isItALeapYear = "a leap year";
  }
}
else {
  isItALeapYear = "year is not leap";
}
console.log(varYear + " is " + isItALeapYear);

Let’s now examine how to determine a year’s status as a leap year using the ternary operator.

const varYear = new Date().getFullYear();
const isItALeapYear = varYear % 4 === 0 ? ( varYear % 100 === 0 ? ( varYear % 400 === 0 ? "it is a leap year" : "it is not a leap year") : "a leap year") : "year is not leap";
console.log( varYear + " is " + isItALeapYear);

Imagine we have a list of employees in an array of objects. If we wanted to verify a certain employee’s ID, for example, we could do something like this:

const employees = [
	{name: 'James',empId: 2133},
	{name: 'Mike',empId: 4325},
	{name: 'Green',empId: 1578},
	{name: 'Donny',empId: null},
	{name: 'Tyson',empId: 2897},
	{name: 'White',empId: 3097},
	{name: 'Angelo',empId: 3515}
]

function validateEmployee(name) {
  const empExists = employees.find(employee => employees.name === name)

  if( empExists && empExists.empId){
	return `Name: ${empExists.name}, ID: ${empExists.empId}`
  }else if( empExists && !empExists.empId) {
	return `Name: ${empExists.name}, does not have an employee ID`
  }else {
	return `Name: ${name}, is not an employee`
  }
}

console.log(validateEmployee('James'))
console.log(validateEmployee('Donny'))
console.log(validateEmployee('Ann'))

In this example, take note of the nested if-else expression. We can use the ternary operator as a shortcut to make this a little easier to read. Let’s have a look at what that might entail.

const employees = [
	{name: 'James',empId: 2133},
	{name: 'Mike',empId: 4325},
	{name: 'Green',empId: 1578},
	{name: 'Donny',empId: null},
	{name: 'Tyson',empId: 2897},
	{name: 'White',empId: 3097},
	{name: 'Angelo',empId: 3515}
]

function validateEmployee(name) {
  const empExists = employees.find( employee => user.name ===	name)
  
  return empExists && empExists.id ?
  `Name: ${empExists.name}, ID: ${empExists.id}` :
  empExists && empExists.id ?
  `Name: ${empExists.name} does not have an ID` :
  `Name: ${name} is not a employee`
  
}

console.log(validateEmployee('James'))
console.log(validateEmployee('Donny'))
console.log(validateEmployee('Ann'))

It appears to be complicated, I know what you’re thinking, but don’t worry; it’s not as awful as you think. Let’s dissect it into smaller pieces so that it can make more sense. Nested ternary operators can be viewed in the following way.

The following line of code is run if the first condition is satisfied. If the first condition in our test is false, we move on to the second condition and proceed as if it were a single ternary operator. Naturally, we should restrict how deeply nested our ternary operators can go. Even if we improve the readability of our code, using too many ternary operators in a row can degrade it. Therefore, we should become familiar with the appropriate times to apply it.

Examples of ternary operators in JavaScript

Let’s look at some ternary operator instances.

Executing several statements using the ternary operator in JavaScript

The ternary operator is used in the following example to carry out many operations, each separated by a comma. For instance:

let auth_status = true;
let next_url =  auth_status
  ? (alert('Success.You will redirect to dashboard area'), '/dashboard')
  : (alert('Access not granted'), '/403');

// redirecting to the next_url here
console.log(next_url); // '/dashboard'

The comma-separated list’s last item is the value that the ternary operator returned in this case.

A simplified example of a ternary operator

See the example below:

let blocked = 1;
let varResult = blocked != 1 ? true : false;
console.log(varResult)

The varResult variable is set to false if the blocked value is 1 and to true otherwise. In this instance, you can make it simpler by employing the following Boolean expression:

let blocked = 1;
let varResult = blocked != 1;

Example of using multiple ternary operators in JavaScript

The example that follows demonstrates how to combine two ternary operators in a single expression:

let speed = 70;
let varMessage = speed >= 100 ? ' extra speed' : speed >= 80 ? 'Average' : 'OK';

console.log(varMessage);

Using the ternary operator is a good practice for making the code easier to read. The ternary operators should not be used if the logic comprises numerous if…else lines.

Ternary operator and if…else

The if…else sentence and the ternary operator are related constructs. The primary distinction is that the ternary operator is more accessible and understandable. Let’s look at an example to grasp better how practical and straightforward the ternary operator is to utilize. You can create clear code by using ternary operators.

Check a student’s exam score in the example below to see if they passed. If their score is greater than 50, they did. Compare the ternary and if…else conditional operators.

let score = 60;
// using if else
if ( score >= 50) {
  console.log("Above Average!");
}
else {
  console.log("Below Average!");
}

console.log("-------------------")

// same results using a ternary operator
score >= 50 ? console.log("Above Average!") : console.log("Below Average!");

As presented above, the ternary operator is much simpler to read and comprehend than the if…else construct.

Value assignment with the ternary operator

A value can be assigned to a variable using the ternary operator. It is helpful when you want to provide a variable with a value based on a condition.

You can alternatively assign a value for a variable using the if…else statement, but that seems like a lot of code and is difficult to follow. You can create orderly code by using the ternary operator. Let’s look at an illustration of how to give a variable a value using the ternary operator.

const checkIfYearIsLeap = true;
const daysInYear = checkIfYearIsLeap ? 366: 365;
console.log(daysInYear);

Multiple ternary operator’s conditions

A variable’s value can be determined using the ternary operator to examine multiple conditions. Let’s look at an illustration of how to use a ternary operator to take several conditions.

const numVal = 45;
// check if the given value is divisible by both 3 and 5
const divisibleBy3And5 = ( numVal % 3 === 0 && numVal % 5 === 0) ? true: false;
console.log(divisibleBy3And5);

Here is another illustration of using the ternary operator with many criteria.

let varAge = 28;

// establish students age group based on the provided age value
let ageGroup = varAge < 18 ? "junior" : varAge < 30 ? "average" : "senior";
console.log(ageGroup);

If you’re still unclear about how “average” came to be, read the following for further information. Several conditions are combined to form the ternary operator. The code above skipped the following criterion (age 30) and returned true because the first condition (age 18) was false. See the ternary operator in the code below, which spans numerous lines.

let varAge = 28;
// find age group
let ageGroup = varAge < 18 ? "underage" // if
            : varAge < 30 ? "average"  // else if
            : "senior";            // else
console.log(ageGroup);

Ternary Operator in Loops

Loops can also make use of ternary operators. It is pretty helpful when you wish to check a condition in a loop. Let’s have a look at a ternary operator loop example.

const varNum = [1, 2, 3, 4, 5];
const resVal = varNum.map(num => num > 4 ? "greater than 4" : "less than 4");
console.log(resVal);

Loops with a ternary operator and various conditions

When you need to combine several conditions inside one statement, ternary operators help you write self-explanatory code. See the illustration to get the idea.

const varNum = [1, 2, 3, 4, 5];
const resVal = varNum.map(num => num > 4 ? "greater than 4" : (num < 4 ? "less than 4" : "number is equivalent to 4"));
console.log(resVal);

Conclusion

We have explored a ternary operator in Javascript in this tutorial and how helpful it is for clear code. Every developer or programmer aspires to write clean code since it is a good practice. To shorten the code, use the ternary operator (?:) in JavaScript.

When using an if-else statement in a project, always choose the ternary operator because it is regarded as best practice and makes your code more legible and cleaner. However, be careful not to use the ternary operator when there are several if-else statements together since this can complicate your code.

Similar Posts

Leave a Reply

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