Execute Program

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 .reverse method. This works as we'd expect.

  • >
    const a = [3, 2, 1];
    a.reverse();
    Result:
    [1, 2, 3]Pass Icon
  • 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'Pass Icon
  • 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'Pass Icon
  • .reverse modifies the array it's called on, like .sort does.

  • >
    const numbers = [1, 2, 3];
    numbers.reverse();
    numbers;
    Result:
    [3, 2, 1]Pass Icon
  • >
    const strings = ['k', 'o', 'a', 'l', 'p'];
    strings.sort();
    strings.reverse();
    strings.join('');
    Result:
    'polka'Pass Icon