JavaScript Arrays: Reverse
Welcome to the Reverse lesson!
JavaScript arrays' "reverse" method puts the elements in reverse order.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We can reverse arrays with the
.reversemethod. This works as we'd expect.>
const a = [3, 2, 1];a.reverse();Result:
[1, 2, 3]
This is sometimes useful with sorting. The next example sorts strings in alphabetical order.
>
const strings = ['k', 'o', 'a', 'l', 'p'];strings.sort().join('');Result:
'aklop'
We might want to sort the strings in reverse-alphabetical order instead. No need to write a custom comparison function; we can just sort and reverse.
>
const strings = ['k', 'o', 'a', 'l', 'p'];strings.sort();strings.reverse().join('');Result:
'polka'
.reversemodifies the array it's called on, like.sortdoes.>
const numbers = [1, 2, 3];numbers.reverse();numbers;Result:
[3, 2, 1]
>
const strings = ['k', 'o', 'a', 'l', 'p'];strings.sort();strings.reverse();strings.join('');Result:
'polka'