What is a ternary operator (?:) in JavaScript?


The conditional operator or ternary operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

S.No
Operator & Description
1
? : (Conditional )
If Condition is true? Then value X: Otherwise value Y

Example

You can try to run the following code to understand how Ternary Operator works in JavaScript

Live Demo

<html>
   <body>
      <script>
         var a = 10;
         var b = 20;
         var linebreak = "<br />";

         document.write ("((a > b) ? 100 : 200) => ");
         result = (a > b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);

         document.write ("((a < b) ? 100 : 200) => ");
         result = (a < b) ? 100 : 200;
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 07-Jan-2020

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements