Example of javascript ternary operator usage

  • 2020-05-30 19:25:49
  • OfStack

Example of use of 3 meta operators:

The 3 - bit operator as the name implies requires three operands.

The syntax is the condition ? Result 1: result 2; .here you write the condition in the question mark (?) Is followed by result 1 and result 2 separated by a colon (:). So it's going to be 1 if this is true or 2 if this is true.


<script type="text/javascript">
var b=5;
(b == 5) ? a="true" : a="false";
document.write(" --------------------------- "+a);
</script>

Result: -- true

<script type="text/javascript">
var b=true;
(b == false) ? a="true" : a="false";
document.write(" --------------------------- "+a);
</script>

Result: -- false

Introduction to 3 - bit operators in programming languages

This operator is rare because it has three operands. But it does belong to one of the operators, because it also ends up generating one value. This is different from the normal if-else statement described in section 1 of this chapter. The expression takes the following form:


Boolean expression ? value 0: value 1

If the result of "Boolean expression" is true, the "value 0" is evaluated, and its result becomes the value ultimately generated by the operator. But if the result of "Boolean expression" is false, it evaluates to "value 1," and its result becomes the value ultimately generated by the operator.

Of course, you can switch to the normal if-else statement (described later), but the 3-tuple operator is more concise. Although C prided itself on being a concise language, and the 3-bit operator was mostly introduced for this type of efficient programming, if you're going to use it frequently, you should think twice about it -- it's easy to produce extremely readable code.

You can use the conditional operator for your own "side effects" or for the values it generates. But you should always use it for values, because doing so would clearly distinguish the operator from if-else. Here's an example:


  static int ternary(int i) {
  return i < 10 ? i * 100 : i * 10;
  }

As you can see, if you were to write the above code using the normal if-else structure, you would have a lot more code. As follows:

  static int alternative(int i) {
  if (i < 10)
  return i * 100;
  return i * 10;
  }

But the second form is easier to understand and does not require more typing. So be sure to weigh the pros and cons of 1 when choosing a 3-bit operator.


Related articles: