Guys, isn’t multiplication done before division in JS? Because I was testing around with this code 10 / 2 * 10;
, which the output will equal 50
, so I decided to break it down to find out if multiplication is done before division and will the output be the same? First I multiplied 2 * 10;
and I got 20
, then I divided by the other 10
, like this 10 / 20
, and I got .5
, or 2
, if it’s done the other way around, but none of them equal to 50
, as it suppose to be. So then I decided to test with dividing first. So here is our code again 10 / 2 * 10;
, so I first did 10 / 2;
, which got me 5
, then I multiplied it 5 * 10;
, and got 50
, the same output as typing the whole thing in. So unless I’m making a mistake here, division goes before multiplication not the other way around, right?
Hello!
Mathematically, I believe you are looking at this incorrectly when you try to do the multiplication first.
10/2*10
is the same as 10*10/2
. But performing the 2*10
first changes your initial statement to 10/(2*10)
.
Multiplication and Division have the same precedence in JavaScritpt. When left associative operators (most operators) have the same precedence they are executed left to right.
Take a look a the “Table” that lists precedence here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
So the multiplication is done first, but I just didn’t break it down correctly?
So you’re saying both multiplication and division have the same priority, so multiplication = division, and it just depends where on the line they are?
Yup, unless you use a higher precedence operator like () to change this.
This page tells the precedence of the symobls https://www.dummies.com/web-design-development/javascript-operator-precedence/
Yeah, that’s an abridged list. The full list is at the MDN link I provided.