DIGG IT!
Published
Tuesday, February 22, 2005
at
8:11 AM
.
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 ) == trueThe 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')
}
//falseBe careful with your Boolean expectations, errors can seep into your application if your not careful.
Cheers,
Ted ;)
Also, the line
trace( 'Boolean( "0" ) == ' + Boolean( '0' ) )
will trace as true when published to SWF 7 and false for SWF 6 and 5.
Best regards,
Burak
Burak KALAYCI
http://www.buraks.com
Great point Burak! Different AS compiler versions, different bytecode output.
Cheers,
Ted ;)
Adobe should be ashamed of this garbage. How can they expect their product to be real when they write interpreters like this. Thanks this was helpful!