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
Try this (demo)
var array1 = ["1", "2", "3"];
var array2 = array1.slice(0).reverse();
console.log(array1, array2);
Using slice(0)
creates a new array.
In Situation 1
The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
In Situation 2
you have the same reference. You are printing array1
array before reverse it.
var array1 = ["1", "2", "3"];
var array2 = array1;
console.log(array1); // [ '1', '2', '3' ]
console.log(array2.reverse()); // [ '3', '2', '1' ]
console.log(array1); // [ '3', '2', '1' ]
Array is object in javascript so assigning an array to another array simply assigns its reference so both of them will be pointing to same object. Whereas for this situation it is better to use slice function of array to copy data of array to another like
var array1 = ["1", "2", "3"];
var array2 = array1.slice().reverse();
console.log(array1); // ["1", "2", "3"]
console.log(array2); // ["3", "2", "1"]
reverse()
modifies and returns the original array. See MDN Array.prototype.reverse()
var array1 = ["1", "2", "3"];
var array2 = array1; // point to the same object
console.log(array1); // original array1 (["1", "2", "3"])
console.log(array2.reverse()); // reverses array2 and array1 since they
// point to the same object and returns
// array2 (["3", "2", "1"])
console.log(array1); // check that array1 was reversed (["3", "2", "1"])
console.log(array1.reverse() === array1); // returns true
The problem is that reverse()
change the array itself. That means, if you write var array2 = array1.reverse()
then array1 is reversed. Array1 contains now the reversed entries and on the other side array2 is initialized with this reversed array. Therefor you have the same output.
On the second example with var array2 = array1
you have two variable referencing the same array.
First you print out array1 which result in normal order. As second step you reverse array2 and print it out. The order has changed now. But if you print out array1 again now, the result will be the array in reversed order, because array1 and array2 refer to the same array.
When you call .reverse you are reversing the value, and then returning the array.
var array1 = ["1", "2", "3"]; //Create a new array
var array2 = array1.reverse();//Reverse array1 and assign it to array2
Any changes made to array1
are also reflected in array2
in this case, the confusion arose from the fact that you were printing the value before it was modified.