Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array reverse function unexpected behavior

Tags:

javascript

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 ?
like image 880
m-a.D Avatar asked Apr 24 '16 21:04

m-a.D


People also ask

Can you reverse an array JavaScript?

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.

How do you reverse an array in place in JavaScript?

JavaScript Array reverse() The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.

How do you reverse a function in JavaScript?

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.


2 Answers

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' ]
like image 116
isvforall Avatar answered Sep 23 '22 21:09

isvforall


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.

like image 23
Juan Cortés Avatar answered Sep 24 '22 21:09

Juan Cortés