Javascript Behaviour

I don’t understand why this is happening? I can think of a few workarounds but I want to make sure I understand the fundamentals here.

When I create the two variables, surely that provides me with a copy that I can manipulate. Any help would be much appreciated.

The console output has both the arrays - str1 and str2 exactly the same:
[ ‘k’, ‘e’, ‘y’, ‘e’ ]
[ ‘k’, ‘e’, ‘y’, ‘e’ ]

Reverse changes the array in place. You then do a shallow copy of str1, so the contents of the two are the same. You should search Google or the forums for deep copying.

1 Like

The assignment of str2 to str1 does not create a new array. Arrays/Objects are assigned by reference, not copy. So when you assign str2 to str1 you are merely creating a “pointer” or reference to str1. Anything you do to str2 will actually be done to str1 and anything done to str1 will show up in str2.

3 Likes

Thank you very much. Very helpful

Thank you - that is helpful!