Operator Precedence
Introduction to operator precedence.
We'll cover the following...
Operator precedence
In JavaScript, every line is parsed first, and then interpreted. When a line is parsed, JavaScript follows an order of precedence where an operator with higher precedence is processed first. which in turn becomes an operand for the operator with lower precedence.
Take a quick look at this example.
var var1 = 1 + 2 * 3; // store solution of arithmetic calculation in var1console.log("var1:",var1); // print var1 value
We can see in the above example that the program first takes the product of 2
and 3
before adding 1
, making the answer 7
. This is because of operator precedence. Let’s look at another example.
var var1 = 1 + 2 + 3; // store solution of arithmetic calculation in var1console.log("var1:",var1); // print var1 value
Now in the above example, we do get 6
, an expected answer, because it is the sum of 1
, 2
, and 3
. However, we are not sure about the order of the calculation, because the two +
operators have the same precedence. So when this situation arises in JavaScript, it is solved through Associativity. ...