Interesting arraySet Behavior

A reader pinged me last night with something he was convinced was a bug, but had said that Adobe shot him down and told him it was expected behavior. The behavior in question involved arraySet, a function I rarely use myself, but is useful for folks who want to quickly initialize multiple values in an array.

What he noticed was that when he used arraySet with structs, each array element pointed to the same structure. Here is an example:

<cfset a = []> <cfset arraySet(a,1, 5, {})> <cfset a[1].name = "ray"> <cfdump var="#a#">

The result of this is:

As you can see, I only modified the first array element, but all five were modified. We get this result because the structure created within the arraySet function is copied by to all the array elements, but copied by reference. This is expected (although it trips people up) for structures and other complex data. It is also expected, or should be, that if you use a function for the value in arraySet that it will only be run once. So for example:

<cfset arraySet(a,1, 5, createUUID())> <cfdump var="#a#">

When run this returns:

Again, I don't think any of this is wrong, or even unexpected, but I certainly can see forgetting this myself.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments