It's important to note that Array.reverse()
does two things:
- It mutates the array it's given by reversing it
- It returns a reference to the array that was just reversed
Let's take a look at your examples and what's going on/
Situation One
var array1 = ["1", "2", "3"]; // Creates new array
var array2 = array1.reverse(); // Reverse array1 and stores reference to array1 in array2
// Since array1 and array2 point to the same object, they will have
// the same values since they are pointing to the same object
console.log(array1); // ["3", "2", "1"]
console.log(array2); // ["3", "2", "1"]
Situation Two
var array1 = ["1", "2", "3"]; // Creates new array
var array2 = array1; // array2 now holds a reference to array1
// Same as the previous example, array1 and array2 both have the
// same values since they are pointing to the same object
console.log(array1); // ["1", "2", "3"]
// Now we reverse array2, which reverses array1 AND array2
console.log(array2.reverse()); // ["3", "2", "1"]
// array1 is now also reversed
console.log(array1); // ["3", "2", "1"]
In the second situation, after you call array2.reverse()
, both array1
and array2
become reversed since they're pointing to the same object reference.