The JavaScript conditional operator is a Ternary Operator, which takes three operands. The first operand is condition to evaluate. It is followed by a question mark (?), then an expression (expression1). It is then followed by a colon (:) and second expression (expression2). If the condition is true, then expression1 executes & if the condition is false, then expression2 executes. The conditional operator is a shorthand way to write an if-else statement.
The syntax is as follows
Syntax
condition ? expression1 : expression2;
Where
Example
const isValid = true;
// Conditional operator
const message = isValid ? 'Valid' : 'Failed';
A ternary operator is an operator which takes three operands. The conditional operator is the only Ternary Operator in JavaScript. If the operator requires two operands, then it is a binary operator. If it requires only one operator, then it is a Unary Operator
let a=10
let b=15
let c= (a > b ? 'a is greater than b' : 'a is not greater than b');
console.log(c) //a is not greater than b
Conditional Operator is a shortcut to the If condition. The above code is the same as the following if statement.
let a=10
let b=15
let c:string
if (a > b ) {
c='a is greater than b'
} else {
c='a is not greater than b'
}
console.log(c) //a is not greater than b
We can also add multiple conditions or nested conditions to a Ternary Operator.
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(10,10) //a is equal to b
check(11,10) //a is greater than b
check(10,11) //b is greater than a
b
Read More