Making the hard way easy

The safest way to proceed with comparisons without wasting time tracking obscure bugs and compatibility problems is to use a straightforward approach. First, compare same types only —don't mix Numbers and Strings; second, if mixing is inevitable, force the conversion you want to happen. Finally, avoid comparing things with null; just rely on the fact that conversion to the Boolean type is reliable. This example illustrates these points:

var result = ( a+'' == b+'' );         // String comparison forced
    result = ( a-0 == b-0 );         // Number comparison forced
    result = ( !a == !b );         // Boolean comparison forced 

if ( a != null ) { do_something(a); };   // possibly attracts bugs
if ( a ) { do_something(a); };         // more likely to avoid bugs

var message = "total errors: " + num_errors;   // always safe

© 1997 by Wrox Press. All rights reserved.