JavaScript – Ternary Operator

Following is syntax of ternary operator in JavaScript.

test?expression1:expression2

Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ternary Operator</title>
</head>
<body> <p id="demo"> </p>
<script type="text/javascript">
var ele = document.getElementById("demo");
var now = new Date();
var greeting = "Current time: " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " " + ((now.getHours() < 11) ? "am" : "pm"); 
ele.innerHTML = "" + greeting;
</script>
</body>
</html>

Output is:

Current time: 17:33:14 pm

Here we have used ternary operator to show ‘am’ or ‘pm’ next to current time. It checks hours is less than 11 then it add am or add pm next to time