Execute Program

JavaScript Arrays: Reduce Right

Welcome to the Reduce Right lesson!

JavaScript arrays' `.reduceRight` method is like `.reduce`, except that it begins from the right of the array, at the last element, and moves left.

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • .reduce processes array items from left to right. There's also a less-common variant called .reduceRight. With .reduceRight, the array is processed from right to left.

  • This doesn't matter for many operations, like summing numbers. We get the same sum whether we do 1 + 20 + 300 or 300 + 20 + 1.

  • >
    [1, 20, 300].reduce((acc, current) => acc + current);
    Result:
    321Pass Icon
  • >
    [1, 20, 300].reduceRight((acc, current) => acc + current);
    Result:
    321Pass Icon
  • However, .reduceRight produces a different result when the order of operations matters. In the next example, we concatenate (join) strings in reverse order. .reduceRight begins at the right ('c') and ends at the left ('a').

  • >
    ['a', 'b', 'c'].reduceRight((acc, current) => acc + current);
    Result:
    'cba'Pass Icon
  • Left vs. right is also important for subtraction. .reduce and .reduceRight differ here because 20 - 1 != 1 - 20.

  • >
    [20, 1].reduce((acc, current) => acc - current);
    Result:
    19Pass Icon
  • >
    [20, 1].reduceRight((acc, current) => acc - current);
    Result:
    -19Pass Icon
  • When the order of operations matters, remember that .reduceRight is available!