JavaScript: Reverse Polish notation

Last update: 14 Sep 06:03
Completion rate

In this exercise we have to make a stack machine, that is, an algorithm that computes using reverse Polish notation.

Reverse Polish notation or postfix notation is a way to write mathematical and logical expressions in which the operands are placed before the operation signs. It reads the expression from left to right. When an expression contains an operation sign, the corresponding operation is performed on the two closest operands to its left. The result of an operation replaces the sequence of its operands and the sign in the expression, and then the expression is evaluated further by the same rule. Thus, the result of the entire expression is the result of the last evaluated operation.

For example, the expression (1 + 2) * 4 + 3 in postfix notation will look like this: 1 2 + 4 * 3 +, and the result of the calculation: 15. Another example is the expression: 7 - 2 * 3, in postfix notation: 7 2 3 * -, result: 1.


Export as default a function that takes an array where each element is a number or an operation sign (+, -, *, /). The function should return the result of the calculation in reverse polish notation. If at some point division by zero occurs, the function must return null.

calcInPolishNotation([1, 2, '+', 4, '*', 3, '+']); // 15
calcInPolishNotation([7, 2, 3, '*', '-']); // 1

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
hours of theory