//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';
console.log(score_checker);
//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' : "";
}
console.log(check_number(7));
console.log(check_number(6));
console.log(check_number(10));
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.
0 Comments