Chris Chris - 6 months ago 7
Javascript Question

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?

Answer

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.