1

Let me explain:

function PalindromeTwo(str) {
  str = str.split('');
    var arr = [];
    str.forEach(function(it){
      if( (/[a-z]/i).test(it) ){
          arr.push(it);
        }
    })
    var reverseArr = arr.reverse();
    return reverseArr.join('').toUpperCase() === arr.join('').toUpperCase();
}

PalindromeTwo("hello, there");

In this example, it returns true when it should return false because the line var reverseArr = arr.reverse() reversed not just reverseArr but arr, i.e. the original variable, as well. Why is that?

  • 1
    Note, you could also just traverse the `str` array in backwards order with a `for` loop and then not have to reverse the resulting `arr`. – jfriend00 Sep 03 '15 at 16:17

2 Answers2

5

Yes, reverse reverses the array in place. You can create a copy before reversing though by using slice.

var copy = arr.slice();
copy.reverse();
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
5

Why is that?

Because the specification says so:

The elements of the array are rearranged so as to reverse their order. The object is returned as the result of the call.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93