Ternary Operator and it's superpowers

Ternary Operator and it's superpowers

Use cases where we can use the ternary operator to make things easier and quicker.

ยท

2 min read

If you have been using if else statements frequently in your code for checking any condition then you will be finding the ternary operator handy, it is a very good alternative of if...else statement.

The ternary operator in JavaScript takes 3 operands, first a condition that is followed by a (?) question mark and then an expression to execute if the condition is true followed by a (:) colon and then the expression to execute if the condition is false.

Syntax:

condition ? expressionToExecuteIfTrue : expressionToExecuteIfFalse

Simple Example:

const age = 20;
const drivingLicence = age >= 18 ? "Has Driving Licence" : "Don't have driving Licence";
console.log(drivingLicence ); // "Has Driving Licence"

Comparison with if..else

//if else
    if (guess > secretNumber){
          if(score > 1){
            document.querySelector('.message').textContent = '๐Ÿ˜‰ Too High'
          }else{
            document.querySelector('.message').textContent = '๐Ÿ™ You lost'
          }


    }else if (guess < secretNumber){

          if(score > 1){
            document.querySelector('.message').textContent = '๐Ÿ˜ Too Low'
          }else{
            document.querySelector('.message').textContent = '๐Ÿ™ You lost'
          }

    }



//Above code refactored with ternary operator and from two blocks of if else to only one block

    if(guess !== secretNumber){
          if(score > 1){
            //using ternary operator here
            document.querySelector('.message').textContent =  guess>secretNumber ? '๐Ÿ˜‰ Too High' : '๐Ÿ˜ Too Low'
          }else{
            document.querySelector('.message').textContent = '๐Ÿ™ You lost'
          }

    }

You can also use One Ternary Operator Inside Another :


let number = 20;

let marks = number >= 90 ? "A+"

    : number >= 80 ? "A"

    : number >= 70 ? "B+"

    : number >= 60 ? "B"

    : number >= 50 ? "C+"

    : number >= 40 ? "C"

    : "F";

console.log(`Here is your marks grade ${marks}`);

In this way, you can write cleaner code than using the if-else statement


If you have any issues or questions about it, feel free to contact me. Thank you ๐ŸŒŸ for reading! like, share and subscribe to my newsletter for more!

๐Ÿ”—Debasish Lenka

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!

ย