The array method join
(MDN ref) does not change the original array, it returns a string. Other methods do change the original array, such as push
(MDN ref) or shift
(MDN ref).
But you are correct, arrays are references. For example, consider this snippet. Try to think what the result will be before running it.
var arr1 = "john".split('');
var arr2 = arr1.reverse();
var arr3 = "jones".split('');
arr2.push(arr3);
console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));
console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));
I got the snippet from this site. Here is the explanation:
The reverse()
method returns a reference to the array itself (i.e., in this case, arr1
). As a result, arr2
is simply a reference to (rather than a copy of) arr1
. Therefore, when anything is done to arr2
(i.e., when we invoke arr2.push(arr3);
), arr1
will be affected as well since arr1
and arr2
are simply references to the same object.