Operator Precedence

Have you ever wondered why this expression evaluates to 7 and not, say, 9?

const result = 1 + 2 * 3
console.log(result) // 7

It turns out JavaScript has specific rules for determining the order in which operations are performed. These rules are defined by operator precedence and associativity.

Operator Precedence determines the order in which different operators and syntax are evaluated. Whichever has the higher precedence is executed first.

In our example, the multiplication (*) operator has a higher precedence than addition (+). That's why 2 * 3 is evaluated first, resulting in 6, and then 1 + 6 gives us 7. Not to mention the operator assignment (=) has the lowest precedence, so it's executed last.

If you look through the MDN docs, you will notice that some operators have the same precedence. That's when operator associativity comes into play. Press → to see.