The Conditional Operators






The Conditional Operators

The conditional operators are a way of testing for specific conditions: equality, identity, relational, and logical. Though the processes may differ, and they range from simple to complex, the result of using such operators is one of two values: TRue or false.

The Equality and the Identity (String Equality) Operators

One of the most common operators used in a conditional expression is the equality operator, ==. It is used when a variable is compared with another variable or literal value, and based on the result, an action or set of actions is triggered:

// at some point  in application, assign 3 to variable nValue
var nValue = 3;
...
if (nValue == 3) ...

In this example, if the variable nValue is equal to 3, what follows (represented by the ellipses in the text) is processed. Otherwise, the flow of the program skips over the code block and goes to the first statement following.

Be careful not to leave off the second equals sign (=). If you do, the expression becomes one of assignment, not conditional testing. The variable nValue is assigned the value of 3. Since the assignment was successful, it returns TRue. It always returns TRue. A JavaScript error doesn't occur, and as such, it may be hard to spot this error in debugging.


As with the addition operator, the equality operator converts the variable's data type to facilitate the evaluation of the expression. If one value is numeric and the other is string, comparing both is successful if the value is "typographically" the same:

var nValue = 3.0;
var sValue = "3.0";
If (nValue == sValue) ...

This can lead to some interesting and unexpected side effects. In particular, the equality operator is implicitly used in the switch statement, which means that both of the following cases are applicable if the switch expression evaluates to "3.0":

case 3.0: ...
case "3.0": ...

Starting with JavaScript 1.3, a new operatorthe identity, or strict equality operatorwas added specifically to test on both value and type. Unlike standard equality, the strict equality operator won't return success unless both operands are the same and have the same data type:

if (nValue === sValue) ...

In addition to testing for both equality and identity, you can also test for not equals and strict not equals. The not equals operator is !=:

if (sName != "Smith") ...

The strict not equals operator is !==:

if (sName !== "Smith")...s

Here is where the difference between the two operators is most apparent. In Figure, a numeric value is tested against a string with equality and strict equality, and a string value is tested against a numeric with not equals and strict not equals.

Testing for precision between equals and strict equals

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Identity and Equality</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[

var sValue = "3.0";
var nValue = 3.0;

if (nValue == "3.0") alert("According to equality, value is 3.0");

if (nValue === "3.0") alert("According to identity, value is 3.0");

if (sValue != 3.0) alert ("According to equality, value is not 3.0");

if (sValue !== 3.0) alert ("According to identity, value is not 3.0");

//]]>
</script>
</head>
<body>
<p>Some page content</p>
</body>
</html>

In the first case, the numeric 3.0 is tested against the string-based "3.0" with the equality operator. The result is true, and the dialog window opens. However, this comparison fails with strict equality, and the second dialog window is not opened.

In the third case, the string 3.0 is tested against the numeric 3.0. The not equals test fails, because to this operator, both values are the same. However, with the strict not equals operator, this comparison does evaluate to true, and the alert window opens.

Figure also introduces a shortcut method of processing one statement associated with a conditional statement. In this case, curly braces aren't necessary because the association is quite readable, and there is only one statement being processed.


As you can see in Figure, the strict equality operator is much more precise. If this is so, you might wonder why it's not more widely used.

The equality operator and its converse, not equals, have been around since the beginning of JavaScript and are supported by all JS engines. The strict equals/identity operator and its converse were added late in the game, with JavaScript 1.2. In addition, with the first release of the ECMA 262 specification, the strict equals operator was dropped, and only added back in with ECMA 262, Version 3.0. As such, support for strict equals isn't guaranteed in all browsers and by all JS engines.

Unless you can control which browser accesses your script, you need to assume that the identity or strict equals operator isn't supported. In a few years, as some of the older browsers finally die out, the strict equals operator will, most likely, become more widely used.

Testing for equality is helpful, but sometimes you need to test a range of values, not just for a specific value. Enter greater than and less than.

Other Relational Operators

A relational operator is one in which one operand is compared to another and depending on the result, one or more lines of code are processed. The equality and strict equality operators are relational operators, except sometimes we want relational operators to also match when a value is either greater than or less than anothernot just equals.

The greater than operator (>) returns true if the right operand is of less value than the operand on the left. The greater than or equals operator (>=) returns true if the right operand is of less or equal value to the operand on the left:

var nValue = 1.0;
if (nValue > 3.0)  // false
...
if (nValue >= 1.0) // true
...
if (nValue >= 0.5) // true
...

The less than operator (<) returns true if the right operand is of greater value than the operand on the left. The less than or equals operator (<=) returns true if the right operand is greater than or equal to the value of the operand on the left, as demonstrated in the following test variations:

var nValue = 1.0

if (nValue < 3.0) // true
...
if (nValue <= 1.0) // true
...
if (nValue <= 0.5) // false
...

Like equality, type conversion occurs implicitly between numeric and string values with the less than/greater than operators. So the following evaluates to true:

sValue = "1.0";
if (sValue >= 2.0) // true

String conversion only occurs when the format is right. For instance, JavaScript does not convert "one" to "1" or "1.0" when doing implicit conversion.

Testing to see if a value is greater than or less than another is useful, but so is testing to see if a variable or expression result is within a range of values. In Figure, a variable is tested to see if it falls within a given range, 0 to 100 inclusive, which means that the value could also be 0 or 100. It's also tested in the range between 0 and 100, excluding the values of 0 and 100. Final tests check whether the value is over 100, or less than zero (0). An appropriate message is displayed based on the result.

Testing within a range of numbers

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Testing value in range</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[

var nValue = 0;

if (nValue >= 0 && nValue <= 100) {
   alert("value between 0 and 100, inclusive");
} else if (nValue > 0 && nValue < 100) {
   alert("value between 0 and 100 exclusive");
} else if (nValue > 100) {
  alert ("value over 100");
} else if (nValue < 0) {    
  alert ("value is negative");
}

//]]>
</script>
</head>
<body>
<p>Some page content</p>
</body>
</html>

The first two comparisons rely on additional operators to establish the range: the logical operators. One such, &&, was introduced in the bitwise operator section. We'll look at these in more detail later, but first, let's check out JavaScript's one and only ternary operator.

The One and Only JavaScript Ternary Operator

The operators we've looked at in this chapter have been unary (one operand), or binary (two operands). There is one ternary operator in JavaScript, the conditional operator, which works with three operands. Following is an example of its use:

var nValue = 1.0;
var sResult = (nValue > 0.5) ? "value over 0.5" : "value not over 0.5";

In this example, sResult is set to "value over 0.5" because the condition evaluates to true, resulting in the second operand being returned. Here's the format of the conditional operator:

condition ? value if true; value if false;

The conditional operator becomes, in effect, a shortcut method for the fairly common, "if (expression), do this; otherwise, do that," such as in the following code:

var stateCode = 'OR';
var taxPercentage = 0.0;
if (stateCode == 'OR') {
   taxPercentage = 3.5;
} else {
   taxPercentage = 4.5;
}

Converting for use in a conditional operator, the code becomes:

var taxPercentage = (stateCode == 'OR') ? 3.5 : 4.5;

It's both a handy shortcut, as well as a readable one, so its use is fairly common. There's more on this operator later in the book when it's used to resolve browser differences.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows