3

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?

3
  • 2
    Because it is done by reference and returns a pointer to the array as in the docs Commented Jun 5, 2016 at 21:23
  • 2
    === already returns a boolean. Commented Jun 5, 2016 at 21:27
  • Also note that [0,1,2] === [0,1,2] --> false, since === returns true for operands of type object, only if they reference the same object. Contents aren't considered. Commented Jun 5, 2016 at 21:32

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.