arr.Append() vs. arr.Push() in ColdFusion

859 views Asked by At

What is the difference between

<cfscript>
   i = []
    
   i.push(1)

   i = []

   i.append(1)
</cfscript>

?

They both seem to have the same results.

2

There are 2 answers

2
user12031119 On BEST ANSWER

In addition to James A. Mohler's answer where the return value is different for each function, there's another distinction between the two. For append(), there's also an additional optional boolean parameter merge which if set to true (default) will merge to the source array. If false, it will add the array as an additional element at the end. For your example of appending a single element to the array, setting the merge parameter to either true or false changes nothing. However, if you're appending 2 arrays together, the difference is clear. For example

<cfscript>
   i=[1,2,3,4,5];
   i.append([6,7], true);
   writeDump(i);

   i=[1,2,3,4,5];
   i.append([6,7], false);
   writeDump(i);

   i=[1,2,3,4,5];
   i.push([6,7]); // Works the same as append(..., false);
   writeDump(i);
</cfscript>

EDIT (from James A. Mohler's comment)

Results
i.append([6,7], true); [1,2,3,4,5,6,7]
i.append([6,7], false); [1,2,3,4,5,[6,7]]
i.push([6,7]); [1,2,3,4,5,[6,7]]

You can see the gist here.

0
James A Mohler On

If you run this

<cfscript>
    
    i = []
    
    writedump(i.push(1)) // returns array length
    writedump(i.append(1)) // returns array
    
</cfscript>

You can see that they give different responses.

enter image description here