Conditional Operators (Ternary)


Conditional Operators (Ternary)

The conditional (ternary) operator in JavaScript is the only one that accepts three operands: a condition and a question mark (?) followed by a condition, an expression to run if the condition is true followed by a colon (:), and lastly, an expression to execute if the condition is false. The if this operator commonly replaces statement.

function getFee(isMember) {
return (isMember ? '$2.00' : '$10.00');
}

console.log(getFee(true));
// expected output: "$2.00"

console.log(getFee(false));
// expected output: "$10.00"

console.log(getFee(null));
// expected output: "$10.00"

A ternary operator analyses a condition and then runs a code block in response to it. It has

the following syntax: condition?
expression1:expression2:expression3:expression4:expression5:expression6:expression

  • The test condition is evaluated using the ternary operator.
  • Expression1 is run if the condition is true.
  • Expression2 is run if the condition is false.

The ternary operator has three operands, as indicated by its name. A conditional operator is another name for it.

Example No.1:

<html> <body> <h2>Knowledge2life</h2> <input id="age" value="23" /> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { let voteable; let age = Number(document.getElementById("age").value); if (isNaN(age)) { voteable = "Input is not a number"; } else { voteable = (age < 18) ? "Too young" : "Old enough"; } document.getElementById("demo").innerHTML = voteable + " to vote"; } </script> </body> </html>

OUTPUT:

Knowledge2life