Nested Ternary Operator in JavaScript

This article will delve into the concept of the nested ternary operator in JavaScript.

Ternary operator

  • The ternary operator is represented as (?:) .
  • It is a blend of a question mark and a colon.
  • It can be utilized instead of the if-else statement.
  • It represents conditional blocks in a concise way.
  • It permits us to read the code with simplicity.
  • Syntax:

    Example
    
    condition ? expression_if_true : expression_if_false
    

The syntax above depicts the sequence of a conditional expression followed by a ternary operator (?:) and then an expression to evaluate the truthfulness of the conditional statement. When the expression evaluates to true, the statement following the question mark (?) is executed. Conversely, if the expression evaluates to false, the statement following the colon (:) is executed.

Parameters of ternary operator

Criterion: It is an expression that serves as a value in programming.

Conditional_expression: This type of expression is commonly used to evaluate if a certain condition is true or false.

When the condition is not met, the code within the expressioniffalse block will be executed.

Initially, we will develop a program to determine a candidate's eligibility to vote by using an if-else statement.

Code:

Example

var age = 15;

if(age >= 18)
{
    console.log("Eligible for vote");
}
else 
{
    console.log("Not Eligible for vote");
}

Output:

The output indicates that the candidate is ineligible to participate in voting.

Next, we'll proceed to develop the identical program using the ternary operator to observe the contrast.

Code:

Example

var age;
console.log((age >= 18)? "Candidate is eligible for vote" : "Candidate is not eligible for vote" );

It is noticeable that the code becomes more concise and condensed into a single line when utilizing the ternary operator, making it a significant benefit of its use.

Explanation:

Within the provided code snippet, an initial condition is established involving a variable named "age" initialized with a value of "15". Subsequently, a conditional expression evaluates whether the age is greater than or equal to 18. Given that the age is not greater than or equal to "15", the statement is deemed false. Consequently, the subsequent code block following the colon is executed, indicating that the individual is eligible to vote.

Output:

It is evident from the output that the condition is not met, therefore the individual is ineligible to vote.

We can employ the ternary operator to develop a program that assigns ratings to students based on their achieved marks.

Example

const score = 85
let scoreRating

if (score > 80) {
  scoreRating = "Excellent"
} else {
  scoreRating = "Can Do Better"
}

console.log(scoreRating)

Explanation:

Within the provided code snippet, an initial condition is established featuring a variable named "score" initialized with a value of 85. Subsequently, a conditional statement evaluates if the score is equal to or surpasses 80. Given that the score exceeds 80, the condition evaluates to true, prompting the output of "Excellent."

Output:

It is observable in the output that the condition evaluates to true.

The concept of the ternary operator has been grasped. Next, we will delve into the nested ternary operator.

Nested ternary operator

Nested ternary operators can be utilized in a manner akin to nested if-else blocks, enabling the handling of more intricate decision-making processes. This involves incorporating a ternary operator within another ternary operator.

To begin, we will create a program that identifies the largest number among four provided numbers by employing nested if-else statements.

Code:

Example

var number1 = 45 ,
  number2 = 12,
  number3 = 15;
var biggest;
if (number1 >= number2) {
 
  if (number1 >= number3) {
    biggest = number1;
  } else {
    biggest = number3;
  }
} else {
  if (number2 >= number3) {
    biggest = number2;
  } else {
    biggest = number3;
  }
}
console.log(biggest);

Output:

We can observe that the output shows the largest number.

Next, we'll create the identical program using the nested ternary operator.

Code:

Example

var num1 = 45 ,
 num2 = 12,
 num3 = 15;

var largest = num1 >= num2 ? (num1 >= num3 ? num1 : num3) : num2 >= num3 ? num2 : num3;
console.log(largest);

It has been observed that the line of code is smaller when using a nested ternary operator in comparison to a nested if-else statement.

Explanation:

The code snippet above initializes three variables named "num1", "num2", and "num3" with values 45, 12, and 15 correspondingly. Subsequently, a series of ternary operators is employed to determine the largest number among them.

The initial condition verifies if num1 is greater than or equal to num2. If num1 is indeed greater than or equal to num2, then a secondary condition is evaluated to determine if num1 is greater than or equal to num3. If this condition holds true, then num1 is identified as the largest number. Conversely, if the condition is false, then num3 is recognized as the largest number.

When num1 is not greater than or equal to num2, it indicates that num2 is the larger number. Subsequently, a nested condition evaluates if num2 is greater than or equal to num3. If this condition is true, then num2 is identified as the largest number. Conversely, if this condition is false, num3 is considered the greatest number.

Output:

We can observe the result showing the highest number identified through the nested ternary operator.

We will create a software application that assesses the air quality and provides feedback depending on a set of conditions.

Code:

Example

var air_quality_index = 51;
var outcome =
  air_quality_index > 300
    ? "Air quality is worst."
    : air_quality_index > 200
    ? "Air quality is bad." 
    : air_quality_index > 100
    ? "Air quality is moderate."
    : "Air quality is good.";
console.log(outcome);

Explanation:

The code snippet shown above begins by declaring a variable named "airqualityindex" with a value of 51. Subsequently, a series of ternary operators are used to evaluate and determine the air quality based on this index.

The initial condition verifies if the airqualityindex exceeds 300. If this condition is met, the result will be "Air quality is at its worst." If not, a secondary condition is evaluated to determine if the airqualityindex is over 200. If true, the result will be "Air quality is poor." If false, a further nested condition examines whether the airqualityindex surpasses 100. If this condition is true, the output will be "Air quality is moderate."; otherwise, it will be "Air quality is good."

Output:

It is observable that the result showcases the air quality by utilizing the nested ternary operator.

Conclusion:

In this article, we have explored the concept of the nested ternary operator in JavaScript. By contrasting it with the if-else and nested if-else statements, we have gained a better understanding of both the ternary operator and its nested version.

Input Required

This code uses input(). Please provide values below: