3

What is the difference between

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

   i = []

   i.append(1)
</cfscript>

?

They both seem to have the same results.

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
  • OT: Since append() seems to contain all of the same functionality of push() - and more - kind of makes you wonder what was the need for adding push()? – SOS Apr 11 '22 at 11:42
  • 2
    @sos, I think they are just trying to make Coldfusion similar to Javascript syntax. – rrk Apr 11 '22 at 14:44
  • 2
    @rrk - Yeah, I'd figured something like that, but still doesn't sound particularly useful to create multiple functions that do the same thing :-) – SOS Apr 13 '22 at 14:39

2 Answers2

8

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.

user12031119
  • 1,228
  • 4
  • 14
4

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

James A Mohler
  • 11,060
  • 15
  • 46
  • 72