JavaScript Array Reverse Doubt

I’m in trouble to understand the array method ‘reverse’.
check the example below. Why is it happening?
When I call the method, both arrays are reversing.

To start off, consider that revArray is not an independent object but merely a reference to the same object in memory as array. It is not a copy, but the same object.

When we reverse it, that is an in-place operation and while we may believe only revArray is reversed, we are in fact reversing the array it references, namely, array.

Even if we assign it, we still end up with the same array in both references.

If we wish to keep the original array intact, then we can either iterate in reverse and push values to the new array, or make a shallow copy of the array and reverse the copy.
Eg.

arr = [1,2,3,4,5,6,7,8,9]
brr = arr.slice().reverse()  // using Array.slice() to make shallow copy
console.log(arr)
console.log(brr)
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
[ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]

My own belief is that we should be able to use the iterative approach without reaching for the built-in Array.reverse() method. At least that way we continue to practice at that way of thinking and approaching problems in their most naive form before refactoring.

How much practice does this take?

const reverse = arr => arr.slice().reverse();
1 Like

Thanks a lot for the answer and great solution.
I will follow your advice.

1 Like

Aside

One usage of the reversed array (as it applies to uniform sequences) is in the proof of the sequence sum equation.

[ 1,  2,  3,  4,  5,  6,  7,  8,  9 ]
[ 9,  8,  7,  6,  5,  4,  3,  2,  1 ]
=====================================
 10  10  10  10  10  10  10  10  10

giving us N = 9, so,

9 * 10 === 90

However, we have doubled the outcome since we have two lists, not one, so we divide by 2 to arrive at the actual sum.

90 / 2 === 45

Because it is a uniform sequence (equal difference between terms) we can write this as,

 s = n / 2 * (a + l)

where a is the first element, and l is the last element, and n is the number of terms.

9 / 2 * (1 + 9) => 9 * 5 === 45
1 Like