JavaScript Ternary Operator
JavaScript Ternary Operator is used to return one of the two values based on the result of given condition.
Syntax
The syntax of Ternary Operator is:
condition? value1 : value2
If condition evaluates to true, then value1 is returned, else, value2 is returned.
Examples
In the following example, we take assign a variable x
with either 'Young'
or 'Adult'
based on the condition that age<18
.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var age = 16;
var x = (age < 18)? 'Young' : 'Adult';
document.getElementById('output').innerHTML += x ;
</script>
</body>
</html>
Since the condition is true for given value of age
, value1
which is 'Young'
is returned by the ternary operator.
Change the value for age, and observe the result. For, example, let us take age = 22.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var age = 22;
var x = (age < 18)? 'Young' : 'Adult';
document.getElementById('output').innerHTML += x ;
</script>
</body>
</html>
Since the condition is false for given value of age
, value2
which is 'Adult'
is returned by the ternary operator.
Conclusion
In this JavaScript Tutorial, we learned about Ternary Operator, its syntax, and usage with examples.