Main Page

Shorten negative tests

Consider this example:
var bFound = false;
for (var i=0; i < aTest.length && !bFound; i++) {
if (aTest[i] == vTest) {
bFound = true;
}
}
You can replace the
true
and
false
without changing the meaning:
var bFound = 0;
for (var i=0; i < aTest.length && !bFound; i++) {
if (aTest[i] == vTest) {
bFound = 1;
}
}
This code runs exactly the same way, and you’ve gained seven bytes.
Shorten negative tests
It’s quite common to test whether a value is valid. The most these
negative tests
can do is determine if a
variable is equal (or not equal) to
undefined
,
null
, or
false
, such as in the following:
if (oTest != undefined) {
//do something
}
if (oTest != null) {
//do something
}
if (oTest != false) {
//do something
}
These are all fine, but they can all be rewritten using the logical NOT operator and have the exact same
effect:
if (!oTest) {
//do something
}
How is this possible? Remember way back at the beginning of the book when automatic type conver-
sions were discussed? The NOT operator returns
true
when its operand is
undefined
,
null
, or
false
(it also returns
true
if the operand is
0
). Take a look at the byte savings anytime you replace one of these
negative tests with the logical NOT operator.
577
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 577


JavaScript EditorFree JavaScript Editor     Ajax Editor


©