In algebra, you all know that multiplication and division have a higher precedence than addition and subtraction.
With the expression 1 + 2 * 3, you must first multiply 2 * 3 and then add 1 to the result.
Well, in Javascript, this concept is also valid, it is simply called Operator Precedence.
Example
Precedence range from 1 to 19 :
- Multiplication has a precedence of 13.
- Addition has a precedence of 12.
- Grouping (putting the expression between parenthesis) has the highest precedence. (19)
console.log(1 + 2 * 3);
// The multiplication is done first, the expression turns into
console.log(1 + 6);
// The addition is then evaluated, the result is 7
console.log((1 + 2) * 3);
// The grouped expression is read first, the expression turns into
console.log(3 * 3);
// The multiplication is then evaluated, the result is 9
The order of evaluation is also influenced by the operator associativity.
Associativity is the direction in which the expression is evaluated : right to left or left to right.
Example
Assignment operators are right-associative, which means they are read from right to left :
a = b = 5
// is the same as
a = (b = 5)
Exception
❗ Grouped expressions are not always read first. If you use conditional evaluations, the condition will be checked first, then the expression between parenthesis will be evaluated.
a || (b * c);
// 'a' is evaluated first, then (b * c) is evaluated if 'a' is false
a && (b < c);
// 'a' is evaluated first, if 'a' is true (b * c) is evaluated