Skip to main content
Inspiring
July 27, 2009
Answered

Returning an Array

  • July 27, 2009
  • 3 replies
  • 776 views

I have a function that is returning an array that is a local variable inside the component... i beleive an array is considered a complex data type so does this mean its going to pass a referenece rather than a copy?

<cfcomponent>

     <cfset variables.anArray = NewArray(1) />

     <cffunction name="getList" returntype="array">

          <cfreturn variables.anArray />

     </cffunction>

</cfcomponent>

    This topic has been closed for replies.
    Correct answer -__cfSearching__-

    Update:  Correction:  I forgot that arrays are an exception.

    http://www.coldfusionjedi.com/index.cfm/2009/5/1/ColdFusion-and-Pass-by-Reference-versus-Value

    But confusingly, you can still modify the underlying array under some circumstances. For example:

    <!--- this would modify the underlying array --->

    <cfset arrayAppend( application.myComponent.getList(), "new value")) >
    <cfdump var="#application.myComponent.getList()#" label="getList() contents">

    <!--- this WILL NOT change the array inside the component --->
    <cfset copyOfArray = application.myComponent.getList() />
    <cfset arrayAppend( copyOfArray, "new value")) >

    3 replies

    -__cfSearching__-Correct answer
    Inspiring
    July 27, 2009

    Update:  Correction:  I forgot that arrays are an exception.

    http://www.coldfusionjedi.com/index.cfm/2009/5/1/ColdFusion-and-Pass-by-Reference-versus-Value

    But confusingly, you can still modify the underlying array under some circumstances. For example:

    <!--- this would modify the underlying array --->

    <cfset arrayAppend( application.myComponent.getList(), "new value")) >
    <cfdump var="#application.myComponent.getList()#" label="getList() contents">

    <!--- this WILL NOT change the array inside the component --->
    <cfset copyOfArray = application.myComponent.getList() />
    <cfset arrayAppend( copyOfArray, "new value")) >

    Participating Frequently
    July 27, 2009

    No, it should pass a copy.  Passing a reference would be dangerous when you consider it would allow you to alter private variables outside of the component (which would completely defeat the purpose of using variable scope to begin with).  I could be completely off base on this, but I believe the only time coldfusion passes a reference rather than a copy is when you are passing an object.

    joshebyAuthor
    Inspiring
    July 27, 2009

    That was my thought as well, I just wanted a second opinion...  anyone know if this is incorrect?

    Inspiring
    July 27, 2009

    Test