Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a reversed array equal a regular array in javascript?

IE why would code like

var strArr = ["a", "b"];
console.log(strArr.reverse() === strArr ? true : false);

print true if the reversed array has a different order?

like image 272
Chris Avatar asked Jan 27 '26 07:01

Chris


2 Answers

Because reverse reverses the array IN PLACE, so you are comparing the array with itself.

like image 69
Amit Avatar answered Jan 28 '26 21:01

Amit


Actually the Array.prototype.reverse() method morphs the original array to it's reverse and then in addition to that returns a "reference" to this morphed array. Hence the result and the morphed original array becomes the same.

If anyone had asked me before developing this method i would request to keep the original as it is and return a reversed array; alas apparently it wasn't my call.

like image 45
Redu Avatar answered Jan 28 '26 20:01

Redu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!