Javascript Arrays & Objects passed by REFERENCE!

Banging my head for 2 days wondering why when I copy an Array/Object to another variable, then change that other variable, it modifies the original Array as well as the copy!

What a PITA … what is the point of making a copy of something if changes you make to that copy also affect the original??? Who designed this stuff? Sheesh.

var TicketOriginal = {id:5}; // Objects behave the same as Arrays
echo TicketOrginal.id; // 5

var TicketCopy = TicketOriginal; // make a copy
echo TicketCopy.id; // 5

TicketCopy.id = 7; // change the id property of the COPY
echo TicketCopy.id; // 7

echo TicketOrginal.id; // 7 !!!! WTF ????

Who knew about this? Seems a lot of people did not know, and only a few did know.

Haha. Arrays are not primitive types in Javascript. As if in C# and Java :wink:

1 Like