1

So lets say I have a variable called array:

var array = [1,2,3]

when I use the reverse() method it reverses the array, as expected

array.reverse()

but lets say I want to keep the original variable so I make a "temporary" variable

var array = [1,2,3]
var arrayRev = array.reverse()
console.log(arrayRev)
console.log(array)

but array is also reversed. how do I know when the original variable changes and when it doesn't?

Thanks if you can help

Dan
  • 79
  • 4
  • 1
    You need to know about the methods, whether they do the changes in-place or not. reverse does the changes in-place so it changes the original variables value. – Code Maniac Mar 17 '20 at 02:04
  • 3
    `arrayRev = array.slice().reverse()` – Jaromanda X Mar 17 '20 at 02:04
  • when you use an an api function, it's best to refer to its documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse States that the function is destructive and it changes the original array – CodeCodey Mar 17 '20 at 02:06

1 Answers1

1

Try this

var array = [1,2,3]
var arrayRev =[...array].reverse()
console.log(arrayRev)
console.log(array)
iamhuynq
  • 5,357
  • 1
  • 13
  • 36