Always remember complex data types are passed by reference

I am working on a pet project currently that is written primarily in jQuery.  The initial state of the application is set by an  ajax call to a remote CFC method that sends back the data.  I was rushing through the CFC side of things trying to get the code written and came up with something similar to this:

 result = structNew();
 appData = structNew();
 result['apps'] = arrayNew(1);

 appData['appName'] = "help";
 appData['windowTitle'] = "Help Content";
 appData['site'] = "";
 result['apps'][1] = appData;
 appData['appName'] = "cfbloggers";
 appData['windowTitle'] = "ColdFusion Bloggers";
 appData['site'] = "";
 result['apps'][2] = appData;

While this code is completely valid it definitely did not return the expected results.  Since ColdFusion passes complex data types (structures, components, and Java objects, etc.) by reference  both of the structures in my array elements contained the cfbloggers information instead of what I expected.  In the rush to get the code done, I forgot to set appData = structNew() after setting the first array element which would have returned the expected result.  A duplicate() would have worked equally well, but that is a bit of overkill for this simple application.

Edit: As Aaron pointed out, arrays are indeed passed by value as with other simple data types (strings, dates and numbers).


2 thoughts on “Always remember complex data types are passed by reference

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s