To reverse the order of elements in an array in JavaScript, use the reverse() method.
The reverse() method will swap the order of elements in an array such that the first will become the last and so forth.
const numbers = [1, 2, 3, 4, 5]
numbers.reverse()
console.log(numbers) // [5, 4, 3, 2, 1]
The reverse() method is an example of an in-place operation which means the original array is transformed as opposed to just returning a copy of the required output (to be stored in another variable presumably).
Alternatively, an array can be reversed using a for loop. This method is useful for demonstrating your understanding of the swapping process and can be translated into other languages which do not have a built in reverse method for array objects.
const numbers = [1, 2, 3, 4, 5]
for (let i = 0; i < Math.floor(numbers.length / 2); i++) {
const temp = numbers[i]
numbers[i] = numbers[numbers.length - 1 - i]
numbers[numbers.length - 1 - i] = temp
}
console.log(numbers) // [5, 4, 3, 2, 1]
In the for-loop example, a loop repeats a number of times equal to half the length of the array (rounded down). This is max number of loops required to reverse an array because only the first half of the indices in the array need to be known. The indices of the elements to be swapped can be calculated by subtracting the first index from the total length of the array.
A variable is required to temporarily store the value in the first element so that it can be changed to the corresponding value in the opposite element without losing the initial value. The value in the opposite element can then be changed to the temporary value to complete the swapping process.