How to use Ternary Operator in place of if else statements Javascript

You can replace your if else statement in Javascript using Ternary Operator. You can use them for simple if else condition like requirements or you can also use them for nested if else conditions.

//Simple If else condition using Ternary Operator
const score = 15;
const score_checker = score > 20 ? 'Score is grater than 20' : 'Score is less than 20';

//Nested If else conditions can be written using Ternary Operator
function check_number(num) {
    return num > 7 ? 'Number is greater than 7'
        : num < 7 ? 'Number is less than 7'
            : num === 7 ? 'Number is equals to 7' : "";

Score is less than 20
Number is equals to 7
Number is less than 7
Number is greater than 7

In the First code snippet we are using a simple condition where we want to check whether the score constant contains the value greater or less than 20.

In the check_number function we are repelacing nested if else conditions with ternery operators. Where we applying three conditions to check whether the number is greater than 7, or the number is less than 7 or the number is equals to 7.

Live Demo

Was this helpful?