Search Flex Components Free

Custom Search

December 10, 2007

Boolean Conversion Problems

I have witnessed many people (including myself) make mistakes with Boolean Conversion. Here is a small example to explore the problem.&

The following example highlights some of the problems people encounter with Boolean Conversion. Although the differences are subtle, they can wreck havoc in your application if you do not understand the results.

Example:
trace( 'Boolean( 0 ) == ' + Boolean( 0 ) )
trace( 'Boolean( 1 ) == ' + Boolean( 1 ) )
trace( 'Boolean( "0" ) == ' + Boolean( '0' ) )
trace( 'Boolean( "1" ) == ' + Boolean( '1' ) )
trace( 'Boolean( "true" ) == ' + Boolean( 'true' ) )
trace( 'Boolean( "false" ) == ' + Boolean( 'false' ) )
trace( 'Boolean( "Donut" ) == ' + Boolean( 'Donut' ) )
trace( 'Boolean( "" ) == ' + Boolean( '' ) )
trace( 'Boolean( undefined ) == ' + Boolean( undefined ) )
trace( 'Boolean( Null ) == ' + Boolean( Null ) )
trace( 'Boolean( true ) == ' + Boolean( true ) )
trace( 'Boolean( false ) == ' + Boolean( false ) )
myBoolTrue = new Boolean( true )
trace( 'Boolean( myBoolTrue ) == ' + Boolean( myBoolTrue ) )
myBoolFalse = new Boolean( false )
trace( 'Boolean( myBoolFalse ) == ' + Boolean( myBoolFalse ) )

This will result in the following output:

Boolean( 0 ) == false
Boolean( 1 ) == true
Boolean( "0" ) == true
Boolean( "1" ) == true
Boolean( "true" ) == true
Boolean( "false" ) == true
Boolean( "Donut" ) == true
Boolean( "" ) == false
Boolean( undefined ) == false
Boolean( Null ) == false
Boolean( true ) == true
Boolean( false ) == false
Boolean( myBoolTrue ) == true
Boolean( myBoolFalse ) == true

The String based results are often the most puzzling as one would expect that strings might be interpreted. If a String is present, it results in true, if empty false. Also objects are tested if they exist, not if the object evaluates to a Boolean. In the example I pass in a Boolean Object and since it exists, it is true, even when the value is internally false.

The real problems start when you realize that you get different results when you use the if() statement and expect Boolean conversion. For example:

if( "" ){
trace('true')
}else{
trace('false')
}
//true

//But...

if( Boolean( "" ) ){
trace('true')
}else{
trace('false')
}
//false

Be careful with your Boolean expectations, errors can seep into your application if your not careful.

Related Flex Tutorials