If you're from the US, you may be familiar with the old saying, Please Excuse My Dear Aunt Sally or PEMDAS. It represents the order of operations or operator precedence of mathematic equations.
Programming languages have expanded version on these rules, but they follow a similar pattern. Just without the famous phrase.
Let's look at some examples
const a = 5 + 6 * 3;
How many operators do you see in the example above? There are two obvious operators (+ & *) but there's a third less obvious operator: the assignment operator =.
The order of operations in this line of code is pretty easy to follow.
- There's a declaration of a variable named `a`.
- `a` points to a math equation.
- JS calculates the equation:
- 6 * 3 happens. Multiplication part of PEMDAS, or precedence power 15 on the table.
- 5 + 18 happens. Addition part of PEMDAS, or precedence power 14.
- The assignment operator, with precedence power of 3, resolves assigning a value of 23 to our variable
I'll add a comparative operator (precedence power: 12) in the next example, as well as some parentheses (power: 21). I'll also introduce associativity. From the MDN docs:
The difference in associativity comes into play when there are multiple operators of the same precedence.
const b = (16 - 2) + 4 > 1 + 5;
I'll briefly cover what happens in less detail. Pay attention to step two where we encounter associativity.
- Parentheses has the highest precedence: 16 - 2.
- Addition and subtraction both go next, in their associative order: left-to-right
- 14 + 4
- 1 + 5
- Now our logical operator: 18 > 6
- Finally, b is assigned the value of true. 18 is greater than 6.
The above examples don't stray too far from math, and should be easy to understand. There are plenty of edge cases involving operator precedence, probably lots that I haven't even encountered yet.
One tricky example is declaring variables in succession. This just involves an understanding of associativity.
const first = second = 10; console.log(first, second); // #=> output: 10, 10
The assignment operator resolves from right to left, so the first line could be rewritten as:
const first = (second = 10).