In this post, we are going to talk about the precedence of operators. I want to demonstrate it with one of our previous codes. Also, in a typical math course, you might have come across bracket notation and BODMAS rules for solving various problems, but in a programming language, how this is done?

The question is, why does `now - 1996 > now - 2021`

work. It works because javascript has a well-defined order of the operator precedence, i.e., the order in which operations are executed. And to see the precedence of all the different operators, you can check out this convenient precedence table.

But to summarise a few widely used operators, the `grouping`

has the highest precedence of 21, and followed by `Math operators`

with precedence of 17, then `comparison operators`

with precedence of 12 and 13. `Logic Operators`

from 10 to 6 followed by `conditional`

and `assignment`

at 4 and 3 respectively.

Of course, there is no need for you to remember this precedence; no one does! But the idea here is that you should have a general idea about which operators would come first. A broader perspective would be something like this; `grouping`

> `math`

> `comparision`

> `logic`

> `condition`

> `assignment`

.

In fact, here you can see that the precedence of `math`

> `comparision`

. This solves our question of `now - 1996 > now - 2001`

; this is synonymous to `2021 -1996 > 2021 - 2001`

then according to precedence, first comes the `math operators`

so it will result in `25 > 20`

now followed by `comparison operator`

resulting in a boolean `true`

.

This precedence table also consists of the order of execution, which sometimes comes in handy. So if required, you can always refer to the documentation. Also. remember this course will not only help you with basic knowledge but also will help you reading documentations.

Let's assume that the assignment operator is executed from right to left. This `x = y = 25 + 15 - 10`

can be split into `x = y`

and `y = 25 + 15 - 10`

with x and y being `undefined`

; As we are assuming the operation is executed left to right `x will be undefined`

and `y will be equals to 30`

. **But this is not the case**.

The assignment operator is executed from right to left; meaning the value of `25 + 15 -10`

, i.e., `30`

will be assigned to `y`

and this new value of `y`

which is `30`

will be assigned to `x`

. Resulting in both `x`

and `y`

as `30`

.

To be more precise, when javascript looks at this piece of code `x = y = 25 + 15 -2 10`

, javascript will look into all the operators it contains and decides upon what to be executed first. As we already saw that `math`

> `assignment`

; you know what's going to happen, i.e., `x = y = 30`

. Now when it comes to the `assignment operator`

it will be executed from right to left, i.e., `y = 30`

and then `x = y`

where `y`

is `30`

resulting in `x = 30`

.