Miscellaneous Operator

Rate this post

We will discuss two operators here that are quite useful in JavaScript: theconditional operator (? ūüôā and the typeof operator.

Conditional Operator (? ūüôā

The conditional 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.

Sr.No Operator and Description
1 ? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

Example

Try the following code to understand how the Conditional Operator works in JavaScript.

<html>
   <body>
   
      <script type="text/javascript">
         <!--
            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>
      
      <p>Set the variables to different values and different operators and then try...</p>
   </body>
</html>

Output

((a > b) ? 100 : 200) => 200 
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
For any query or issue, feel free to discuss on http://discuss.eduguru.in

Leave a Reply

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

%d bloggers like this: