|
The Conditional Operator
Simply put, the conditional operator is the following: "(
(expression) ? trueValue : falseValue )". This operator fulfills
the same functionality as an if / else statement, but in a kind
of shorthanded form. An expression that evaluates to a Boolean
(true or false) must be placed to the left of the question mark.
If the expression evaluates to true, the first value after the
question mark is returned from the operation. If the expression
evaluates to false, the value after the colon is returned from
the operation. This shorthanded if / else statement is
especially useful to decrease the amount of typing you'll have
to do. It seems to make more sense to me than does the if / else
statement.
The following example, taken from the JavaScript Language
Reference, shows the use of both the less-than operator and the
conditional operator. It is a simple example that shows the use
of the conditional operator very well.
var n = new String("67");
if ((n < 100) ? document.write("The result is true")
: document.write("The result is false"));
The example shows the use of the conditional and less-than
operators nicely. First the variable "n" is created, which holds
the number 67, which is of the string data type. Then an if
statement is started with the conditional operator as the
condition. The "n<100", which is read as "if n is less than
100", obviously compares to true since the value of n is 67,
which is less than 100. This comparison tells the browser to
display the "true" result, so the string "The result is true"
will be written to the screen. If the result was false, the
string "The result is false" would be written to the screen. So
much for the conditional operator.
Bitwise Operators
You might notice in our exploration of the bitwise operators
that they look very much like the various comparison operators.
But in fact they differ hugely in their functionality. A
operator is said to be "bitwise" when its values are the direct
result of a binary computation of some sort. The given integer
is converted to a 32 bit binary number, and then something is
done to it. They are indispensable when working with binary
numbers (decimal equivalents of binary numbers). If the integer
used to represent the binary integer doesn't evaluate to 32 bits
long, JavaScript automatically adds on the required amount of
zeros to achieve the required 32 bit length.
|