Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion string == true OR empty == false?

I am used to using PHP and JavaScript but I have now begun working on a project in Coldfusion.

In PHP I am used to a string being "truthy" and empty/null being "falsy".

This doesn't seem to hold true with ColdFusion (specifically v8).

I want to make the following work but cannot figure out how to make CF see the string as truthy:

<cfset x = "path\to\something.cfm">
<cfif x>
    x is truthy
<else>
    x is falsy
</cfif>

I always get the error: cannot convert the value "path\to\something.cfm" to a boolean

  • isBoolean() sort of works but doesn't feel robust enough.
  • There doesn't seem to be an `isString() -- but this would be problem as above anyway
  • YesNoFormat() strangely give me the same error (quite the opposite of what I would have though it should do)
like image 627
atwright147 Avatar asked Jan 16 '13 14:01

atwright147


2 Answers

ColdFusion has some similar "truthiness" functionality to it.

The following will evaluate to true

  • The strings "true" or "yes" (case insensitive)
  • Any non-zero number
  • The value true

The following will evaluate to false

  • The strings "false" or "no" (case insensitive)
  • Zero
  • The value false

In CF we generally use the len() function to determine if a string has anything in it. Since a non-zero number evaluates to "true" this works.

Your pseudo-code would be, then:

<cfset x = "path\to\something.cfm">
<cfif len(x)>
    x is truthy
<else>
    x is falsy
</cfif>

Since ColdFusion converts nulls to empty strings, using trim() in conjunction would be a good idea, like so: <cfif len(trim(x))>.

There is no isString() function, but there is isValid(): isValid("string",x)

YesNoFormat() simply turns a boolean value into a nicely formatted "Yes" or "No".

like image 101
ale Avatar answered Oct 03 '22 06:10

ale


In addition to ale's answer (<cfif len(x)>), I also wanted to point out that you'll also see people use a slightly different syntax:

<cfif x neq "">
    x is truthy
<cfelse>
    x is falsy
</cfif>

This statement is very close to your original attempt, but it's merely checking to see if it's an empty string, vs. comparing the string to see if it's exactly the same (as was your original attempt).

There's a discussion as to which approach is more efficient and readable here on Stack Overflow at: len(x) better or x NEQ "" better in CFML?

It's all subjective...although I prefer ale's method, I also wanted to point out the other approach as well for completeness.

like image 43
Steve Withington Avatar answered Oct 03 '22 06:10

Steve Withington