What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to it. The conditional or ternary operator has been the only JavaScript operator that accepts three operands: a condition, a question mark (?), an expression to execute if the condition is true, followed by a colon (:), and finally an expression to run if the condition is false. As an alternative to an if-else statement, this operator is commonly used.

Syntax

condition ? expression1 : expression2

condition

The value of an expression that is used as a condition.

expression1

If the condition evaluates to a true value, this expression is performed (one which equals or can be converted to true).

expression2

If the condition is false, this expression is performed (it has a value that can be converted to false).

  • The test condition is evaluated using the ternary operator. The ternary operator has three operands, as indicated by its name. Expression1 is run if the condition is true. Expression2 is run if the condition is false. A conditional operator is another name for it.
  • False expressions include null, NaN, 0, the empty string (" "), and undefined. The outcome of the conditional expression will be the result of executing the expression exprIfFalse if the condition is any of these.

Example 1

// program to check if the student has passed or failed
let scored_marks = prompt('Enter your marks :');
// check the condition
let result = (scored_marks >= 40) ? 'You Passed' : 'You Failed';
console.log(` ${result}the exam.`);

Output

Enter your marks: 64
You passed the exam.

Let's say the user types in 64. The condition scored_marks>= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is "You Passed".

Example 2

// program to check what to serve
let age = prompt('Enter your age :');
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage);

Output

Enter your age: 16
Juice

Let's say the user’s age is 16. The condition age >= 21 is then tested, which returns false. Consequently, the result variable is allocated to the second expression, "Juice".

Nested Ternary Operator

The ternary operator is right-associative, which implies it may be "chained" in the same manner as an if... else if... else if... else chain, i.e., You may also stack one ternary operator within another conditional operator as an expression.

Syntax

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}
// Equivalent to:
function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

NOTE: Nested ternary operators should be avoided wherever feasible since they make your code difficult to comprehend.

Example

// program to check if the student scored good, average or bad
let scored_marks = prompt('Enter your marks :');
// check the condition
let result = (scored_marks >= 40) ? ((scored_marks >= 70) ? 'Good' : 'Average') : 'Bad';
console.log(` You scored ${result} in the exam.`);

Output 1

Enter your marks: 34
You scored Bad in the exam.

Let's say the user scored is 34. The condition scored_marks >= 40 is then tested, which returns false. Consequently, the result variable is allocated to the second expression, "Bad”.

Output 2

Enter your marks: 58
You scored Average in the exam.

Let's say the user scored is 58. The condition scored_marks >= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is another condition that checks the condition scored_marks >= 70, which returns false. Consequently, the result variable is allocated to the second expression, "Average".

Output 3

Enter your marks: 82
You scored Good in the exam.

Let's say the user scored is 82. The condition scored_marks >= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is another condition that checks the condition scored_marks >= 70, which returns True. Consequently, the result variable is allocated to the first expression, "Good".

Out of ternary operator and if-else does it matter which we use? Which is the quickest? Are there any noteworthy changes in performance? Is it preferable to utilize the smallest code feasible whenever possible?

  • Yes, it matters which we use! The second is much easier to read. You're sacrificing one line that says what you want succinctly for nine lines that are effectively cluttered.
  • If there is any difference in performance, it will be insignificant. Concentrate on developing the most straightforward, readable code possible.
  • Not "as soon as feasible," but "as soon as possible without causing harm." Shorter code is, at the very least, theoretically more legible since it concentrates on the important parts rather than on side effects.



ADVERTISEMENT
ADVERTISEMENT