Tuesday, December 24, 2019

Operator precedence (Thứ tự ưu tiên các tóan tử)

Operator precedence determines the way in which operators are parsed with respect to each other. Operators with higher precedence become the operands of operators with lower precedence.

Associativity

Associativity determines the way in which operators of the same precedence are parsed. For example, consider an expression:
a OP b OP c
Left-associativity (left-to-right) means that it is processed as (a OP b) OP c, while right-associativity (right-to-left) means it is interpreted as a OP (b OP c). Assignment operators are right-associative, so you can write:
a = b = 5;
with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

Examples

3 > 2 && 2 > 1
// returns true

3 > 2 > 1
// returns false because 3 > 2 is true, and true > 1 is false
// Adding parentheses makes things clear: (3 > 2) > 1

Table

The following table is ordered from highest (21) to lowest (1) precedence.
PrecedenceOperator typeAssociativityIndividual operators
21Groupingn/a( … )
20Member Accessleft-to-right… . …
Computed Member Accessleft-to-right… [ … ]
new (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
Optional chainingleft-to-right?.
19new (without argument list)right-to-leftnew …
18Postfix Incrementn/a… ++
Postfix Decrement… --
17Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
16Exponentiationright-to-left… ** …
15Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
14Additionleft-to-right… + …
Subtraction… - …
13Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
12Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
11Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
10Bitwise ANDleft-to-right… & …
9Bitwise XORleft-to-right… ^ …
8Bitwise ORleft-to-right… | …
7Nullish coalescing operatorleft-to-right… ?? …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2yieldright-to-leftyield …
yield*yield* …
1Comma / Sequenceleft-to-right… , …