In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop and reverse the array manually, but as we will see, in JavaScript there are much faster ways to achieve our goal:
To start, let's start from the following array which we'll call 'letters':
const letters = ['a', 'b', 'c', 'd','e'];
How to reverse the array itself
An effective method of reversion could be to use the reverse() method, which will alter the array itself on which it is executed. In this way, we could declare the array as a constant and would not need to reassign the result of the method:
const letters = ['a', 'b', 'c', 'd','e']; letters.reverse(); console.log(letters);
The result of the above function will be an array with the values ['e','d', 'c', 'b', 'a']
.
How to get a new reverse array
If you want to assign the result to another variable or constant, you can use the spread operator... , so that we can assign the array elements to a new array:
const letters = ['e','d', 'c', 'b', 'a']; const reversedLetters = [...letters].reverse(); console.log(letters); console.log(reversedLetters);
Thus, the constant letters
will continue to hold the elements ['a', 'b', 'c', 'd', 'e']
, while the constant reversedLetters
will contain the elements ['e','d', 'c', 'b', 'a']
.
There is yet another way by which you can invert an array and get it in a new variable without the need to use the spread operator. It consists of using the slice()
method without passing any parameter, just before inverting the array:
const letters = ['a', 'b', 'c', 'd','e']; const reversedLetters = letters.slice().reverse(); console.log(letras); console.log(lettersreversedLetters);
The constant letters
will contain the elements ['a', 'b', 'c', 'd', 'e']
, while the constant reversedLetters
will contain the elements ['e', 'd', 'c', 'b', 'a']