Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.
console.log(3 + 10 / 2); // 3 + 5 ( 10 / 2 )
// Output: 8
console.log(4 * 5 ** 2); // 4 * 25
// Output: 100
let a;
let b = 20;
let c = 50
console.log((a = b = c));
// Expected output: 50
If there is an expression which contains two operations, For instance:
VAR1 OPR1 VAR2 OPR2 VAR3
// VAR : VARIABLE
// OPR : OPERATION
There will be two possible combinations that this expression behaves in:
( VAR1 OPR1 VAR2 ) OPR2 VAR3
VAR1 OPR1 ( VAR2 OPR2 VAR3 )
Which one the language decides to adopt depends on the identity of OPR1 and OPR2.
If OP1 and OP2 have different precedence level, the operator with the higher precedence goes first, and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.
console.log(3 + 3 * 3); // 3 + 9
// Output: 12
console.log(10 * 10 + 10); // 100 + 10
//Output: 110
For operators of the same precedence, the language groups them by associativity.
let a = b = 10; // Same as: a = (b = 10);
Another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.
let a = 4 ** 3 ** 2; // Same as: 4 ** (3 ** 2);
let b = 4 / 3 / 2; // Same as: (4 / 3) / 2;
let c = 4 * 3 * 2 // Same as: (4 * 3) * 2;
So, operators are first grouped by precedence and then, for adjacent operators that have the same precedence, by associativity.
let num = 1;
let str = "2";
console.log(typeof num + str); // Same as: (typeof num) + str
// Output: "number2";
Hope you enjoy reading this article. If you have any suggestions feel free to reach out me and share informative ideas!..
Thank You,
Hari Krishnan P U
