Fly with code

Get wet inside ocean of code

0%

Precedence And Associativity of Operators

Precedence

Determines how operators are parsed concerning each other.
Operators with higher precedence become the operands of operators with lower precedence.

Example 1

Precedence of + and - are both 14,
Precedence of * and / are both 15
And = has relatively low precedence, which is 3.

1
2
3
4
5
console.log(3 + 4 * 5); // 3 + 20
// expected output: 23

console.log(4 * 3 ** 2); // 4 * 9
// expected output: 36

Example 2

But, when Precedence of operators are equal, then follow the Associativity direction.
For example,

1
2
3
1+2+4 // left-to-right Associativity for '+'
count "1+2" first,
then count "3+4" later.

Example 3

1
2
console.log(1<2<3); // true
console.log(3>2>1); // false

for <, Associativity is left-to-right,
Therefore, in terms of console.log(1<2<3);

1
2
3
4
5
count 1<2, return true
then count true<3,
but, JavaScript is an weakly-typed language, it will activate implicit coercion
And turn 'true' into '1',
then 1<3 will return true,

Same concept, for console.log(3>2>1);

1
2
3
4
count 3>2, return true, but
due to implicit coercion,
it will turn 'true' into '1',
then 1>1, return false.

Additional Knowledge

Operator precedence