Ternary Operator
Ternary Operator​
The
ternary operator
, also known as theconditional operator
, It's easy way to write simpleconditional expressions
. It provides a concise way to evaluate a condition and return one of two values based on whether the condition istrue
orfalse
.
The syntax of the ternary operator:​
Syntax :
(condition) ? expressionIfTrue : expressionIfFalse
How it works:​
- The
condition
is evaluated. - If the
condition
is true, the value ofexpressionIfTrue
is returned. - If the
condition
is false, the value ofexpressionIfFalse
is returned.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
let num = 10;
num%2 == 0 ? console.log('Even'):console.log('Odd');
</script>
</body>
</html>
Output
Even
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
let num = 7;
num%2 == 0 ? console.log('Even'):console.log('Odd');
</script>
</body>
</html>
Output
Odd