In this blog we can see what is ternary conditional operator in TypeScript.
Ternary conditional operator :
The Typescript conditional operator is a Ternary Operator with three operands.
The first operand is an evaluation condition. It is followed by a question mark (? ), and finally by an expression (expression1). The colon (:) is then followed by the second expression (expression2).
If the condition is true, expression1 is executed; otherwise, expression2 is executed. The conditional operator is a shortcut for writing an If then statement.
Syntax:
condition ? expression1 : expression2;
Example :
let a=9
let b=12
let c= (a > b ? ‘a is greater than b’ : ‘a is not greater than b’);
console.log(c) //a is not greater than b
Multiple Conditions in Ternary Operator :
A Ternary Operator can also have Multiple Conditions or Nested Conditions.
Example :
function check(a:number,b:number) {
let c= (a == b ? ‘a is equal to b’ : (a >b) ? ‘a is greater than b’ : ‘b is greater than a’);
console.log(c)
}
check(15,15) //a is equal to b
check(15,12) //a is greater than b
check(20,31) //b is greater than a
For any Help or Queries Contact us on info@crmonce.com or +918096556344