Home > Back-end >  Why is the output 16 and not 11?
Why is the output 16 and not 11?

Time:09-18

I was learning javascript and I came across the following example,

let n = 2;

n *= 3   5;

console.log( n ); 

Since we have used "*=" in the expression I thought the expression is supposed to be n = n * 3 5. If the expression is n = n * 3 5 then shouldn't we get 11? I am getting 16 as the answer. Can someone please explain why is the answer 16 and not 11 ?

CodePudding user response:

Because it follows the order of operation. has a higer priority than *= so if we add brackets to the statement to see it clearer, it would be something like:

let n = 2;
n *= (3   5)
// which means n = n * (3   5)
// which is n = n * 8

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table

CodePudding user response:

Well, There is a hidden parentheses in the 2nd line which means, it must look like this n*=(3 5) >> 8 then 16

CodePudding user response:

Its based on the priority and the order

  1. /,*,% ---> calculated from Left to right.

2. ,- ---> calculated from Left to right

  1. =,-=,*=,/=,%=,&=,^=,|=,>>=,<<= ---> calculated from Right to left
  • Related