Order of variables declared in JS

Would be grateful if someone could explain the logic behind arr and reversed printing out the same value? Why is arr already reversed?

function isPalindrome(str) {
  var arr = str.replace(/\W/g, '').split('')
  var reversed = arr.reverse()

  console.log(arr)
  console.log(reversed)
}

The reverse() method reverses an array in place . The first array element becomes the last, and the last array element becomes the first.

2 Likes

In other words, the reverse() method changes the original array.

If you want to keep the original array, you’d have to spread it into a new array before applying reverse to it like so:

var reversed = [...arr].reverse()
2 Likes

also arr.slice().reverse()

3 Likes

Yeah, that’s how the ancients did it :stuck_out_tongue_winking_eye:

2 Likes