quedemy-logo
javascript-ternary-operator

Javascript Ternary Operator: An Overview

June 4, 2023 · 5 min read

There are several conditional operators in javascript (if...else, switch). In this article, we will discuss the ternary operator and use of the ternary operator.

Table of Contents

What is The Ternary Operator?

  • The ternary operator is a conditional operator that evaluates the expression and returns true or false.
  • The ternary operator determines which expression to execute based on whether the condition evaluates as true or false.
  • The syntax of a ternary operator is as follows:
conditionalExpression ? firstExpression : secondExpression
  • If the returned value from conditionalExpression is true, the ternary operator will execute firstExpression.
  • If the returned value from conditionalExpression is false, the ternary operator will execute secondExpression.
  • When ternary operators return a value, we can store returning value in a variable:
const finalValue = conditionalExpression ? firstExpression : secondExpression

How to Use The Ternary Operator in Place of if Statement

  • We can replace the if statement with a ternary operator.
  • Ternary operator makes our code short, clean, and readable. For example:
const percentage = 60
let resultStatus

if (percentage > 33) {
  resultStatus = "Pass"
} else {
  resultStatus = "Fail"
}

console.log(resultStatus) // output: "Pass"
  • In the above code block, we are using a constant percentage and a variable resultStatus. The statement if checks the condition percentage > 33.
  • If the condition percentage > 33 is true, the value of resultStatus will be Pass.
  • Otherwise, the value of resultStatus will be Fail.
  • Now, we will replace the if...else statement with a ternary operator:
const percentage = 60

const resultStatus = percentage > 33 ? "Pass" : "Fail"

console.log(resultStatus) // output: "Pass"
  • That's how the ternary operator makes our code more cleaner and readable.
  • In the above code block, we are using the string Pass and Fail. But We can also use a function. For example:
function printFail() {
    return "Fail"
}

function printPass() {
    return "Pass"
}

const percentage = 30

const resultStatus = percentage > 33 ? printPass() : printFail()

console.log(resultStatus) // output: Fail
  • If condition percentage > 33 is true, function printPass() will be executed.
  • If condition percentage > 33 is false, function printFail() will be executed.

How to Use Nested Ternary Operators

const percentage = 60
let resultStatus

if (percentage > 33) {
    if (percentage >= 60) {
        resultStatus = "Pass with First Division"
    } else {    
        resultStatus = "Pass with Second Division"
    }
} else {
  resultStatus = "Fail"
}

console.log(resultStatus) // "Pass with First Division"

In the above code block, we have two conditions to check:

  • If percentage > 33 is true, then we again check if percentage >= 60.
    • If percentage >= 60 is true, then we assign the value Pass with First Division to variable resultStatus.
    • Otherwise, we assign the value Pass with Second Division to variable resultStatus.
  • If percentage > 33 is false, then we assign the value Fail to variable resultStatus.
const percentage = 60

let resultStatus =
  percentage > 33
    ? (percentage >= 60 ? "Pass with First Division" : "Pass with Second Division")
    : "Fail"

console.log(resultStatus) // output: "Pass with First Division"
  • In the above code block, We check condition percentage > 33 using the first ?.
  • Then, we check condition percentage >= 60 using the second ? that is nested under the first ?.
  • The following figure shows the nested hierarchy for the above code block:
                    percentage > 33   
                        |
            ---------------------------
            |                         |
            ?                         :
        percentage >= 60             Fail
            |
    -----------------
    |               |
    ?               :
  Pass with        Pass with
First Division  Second Division  

Note: Do not use nested ternary operator if not necessary. As they create more confusion and our code becomes hard to read.

Conclusion

  • Ternary operator is a conditional operator in javascript.
  • Ternary operator executes the expression based on truthy or falsy value.
  • Syntax for the ternary operator is condition ? firstExpression : secondExpression. If the condition is truthy, firstExpression will be executed. If condition is falsy, secondExpression will be executed.
  • We can use a ternary operator in place of if..else. But the Ternory operator can't completely replace if...else.
  • Ternary operator helps to keep code neat and clean. However, we should avoid nested Ternary operators.

FAQs

What is a simple example of a ternary operator?

Consider, you want to check the eligibility for a Vote. Then we can use the ternary operator as: age < 18 ? "Not eligible for Vote" : "eligible for Vote".

When should I use the ternary operator?

Instead of a conditional statement if...else, you can use a ternary operator. Ternary operator helps to make simple decisions based on truthy and falsy values.

quedemy-logo

© 2024 Quedemy. All rights reserved

LinkedIn

Company

About usBlogContact usSitemap