JavaScript – Ternary Operator

Following is syntax of ternary operator in JavaScript.



<html xmlns="">
<title>Ternary Operator</title>
<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;

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

Published by

Mandar Badve

Microsoft web, cloud, mobile developer

Leave a Reply

Your email address will not be published. Required fields are marked *