/

HTML / CSS / JavaScript Tutorial

JavaScript Operator: conditional

[this page | pdf | back links]

In JavaScript, the conditional operator is the (ternary) operator that selects between two possible expressions to evaluate depending on whether an expression is true or false.

 

For example, var3 = (boolval) ? var1 : var2 results in var3 being set equal to var1 if boolval is true, otherwise var3 is set equal to var2.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>table,th,tr,td {border: 1px solid black;
  border-collapse: collapse;}</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Conditional1Example"></code></td>
<td><code id="Conditional1"></code></td>
</tr>
<tr>
<td><code id="Conditional2Example"></code></td>
<td><code id="Conditional2"></code></td>
</tr>
</table>

<script>
document.getElementById("Conditional1Example").innerHTML =
  'var x = (5>3) ? 4+3 : 4-3;';
document.getElementById("Conditional1").innerHTML
  = (5>3) ? 4+3 : 4-3;
document.getElementById("Conditional2Example").innerHTML =
  'var x = (5<3) ? 4+3 : 4-3;';
document.getElementById("Conditional2").innerHTML
  = (5<3) ? 4+3 : 4-3;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Operators


Desktop view | Switch to Mobile