Loosely Typed Languages

On CF-Talk today, someone asked about these two expressions:

<cfset i = 5 />
<cfoutput>
#i GT 0 AND i LT 4#
#i GT 0 LT 4#
</cfoutput>

Obviously the first one will be false (5 is not less than 4), but the second one is true! Why, you ask? Because CF is loosely typed, which means that a given value isn't necessarily a single type (number, boolean, string, date); it can seamlessly move between types as needed.

For instance:

<cfset x = 4 + "5″ />

That's going to result in '9', even though you're adding a number and a string. Back to the original example, what's happening is that the first operation (i GT 0) is evaluated to 'true'. Now it looks like this: true LT 4. 'true' is then coerced into a numeric value (because a number is needed to compare with another number), resulting in this expression: 1 LT 4. That expression obviously evaluates to true.

What's all this mean? You have to be extra careful when using a loosely typed language or you can run into really obscure problems like this, that are very hard to find and fix. Strongly typed languages (where implicit type conversions aren't alloed) won't allow things like this to happen. In this case, the language would have complained that you're comparing a boolean to a number, and aborted with an error message.

Comments are closed.