How to reverse JavaScript array

I need to invert a JavaScript array, and this is what I did.

Given an arraylist:

const list = [1, 2, 3, 4, 5]

The easiest and most intuitive way is to callreverse()Array method.

This method changes the original array, so I can declarelistAs const, because I don’t need to reallocate the result of the calllist.reverse()Regarding this:

const list = [1, 2, 3, 4, 5]
list.reverse()

//list is [ 5, 4, 3, 2, 1 ]

You can pair this method with the scatter operator to first copy the original array and then reverse it, so the original array will remain unchanged:

const list = [1, 2, 3, 4, 5]
const reversedList = [...list].reverse()

//list is [ 1, 2, 3, 4, 5 ] //reversedList is [ 5, 4, 3, 2, 1 ]

Another way is to useslice()No parameters are passed:

const list = [1, 2, 3, 4, 5]
const reversedList = list.slice().reverse()

//list is [ 1, 2, 3, 4, 5 ] //reversedList is [ 5, 4, 3, 2, 1 ]

But I found that the spread operator is better thanslice().

Download mine for freeJavaScript beginner's manual


More js tutorials: