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 array2 = array1.reverse();
console.log(array1); // ["3", "2", "1"]
console.log(array2); // ["3", "2", "1"] Why this doesn't work ?
Situation 2 :
var array1 = ["1", "2", "3"];
var array2 = array1;
console.log(array1); // ["1", "2", "3"]
console.log(array2.reverse()); // ["3", "2", "1"] Why this works ?
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
JavaScript Array reverse() The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
Use reverse() function in JavaScript to reversal the array of characters i.e. [ 's', 'k', 'e', 'e', 'G', ' ', 'r', 'o', 'f', ' ', 's', 'k', 'e', 'e', 'G' ] Use join() function in JavaScript to join the elements of an array into a string.
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' ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With