The Order of Operations

By: Dusty Arlia
Published on August 23, 2012
Last Updated on Thursday, July 16, 2015 at 9:09 PM
Total Updates: 4

Whenever you have to perform different mathematical operations in the same JavaScript statement, you need to figure out which operator has the highest precedence. Equations are not calculated left to right. Instead, multiplication and division will come before addition and subtraction. If you need addition or subtraction to be performed first use parentheses. For example:

(5 + 10) * 2   //5 gets added to 10
               //before being multiplied by 2

You can even use parentheses to make your code easier to read. For example:

5 + (10 * 2)

The parentheses have no impact on the order of operations on this previous example, but it does make it easier to read.

Here's one last example to make sure you understand the order of operations:

3 * 4 + 8 / 2     //This should equal 16

Comments:

Ad:

Ad: