I would like to understand why situation 1 and situation 2 don\'t return the same results.
Situation 1 :
var array1 = [\"1\", \"2\", \"3\"];
var arra
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array. Thus, it does not return the reversed array.
CHECK the manuel. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
It's important to note that Array.reverse() does two things:
Let's take a look at your examples and what's going on/
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"]
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.