JavaScript Variables and Operators

106 65
Each of the examples we have looked at so far involves one operation. Often when we are performing operations, we will want to incorporate several operations together into the one command. This can result in several possible results depending on the order in which the operations are performed. Fortunately, JavaScript will always use the same rules for working out which order to calculate things in as you learned back at school - with a slight modification for the operators that you didn't have back then.


  1. ++variable and --variable are always performed first since having the operator in front indicates that we want to add or subtract one before using the result in the subsequent calculation.
  2. Multiplication, division, and taking remainders are performed next, moving left to right.
  3. Addition and subtraction are performed next also moving from the left.
  4. The variable++ and variable-- operations are performed last so that the original values that the variables have can be used in the calculations before the value in the variable itself is changed.

If we need to force an addition or subtraction to take place before the multiplications and divisions then we need to place that calculation inside of parentheses. Anything in parentheses is done before any multiplications and divisions.

Here are a few examples. I have put the answers on the right so that you can see what result JavaScript would produce were it to perform these calculations.

1 5 + 3 * 6 = 232 4 * 7 / 2 + 3 = 173 17 % 3 + 22 * 5 = 1124 (5 + 3) * 6 = 485 4 * 7 / (2 + 3) = 5.6

With 1 the multiplication is performed before the addition and so three times six is eighteen plus five gives twenty three.

In 2 we multiply the four and seven together first and then divides by two to give fourteen to which the three is finally added.

3 takes the remainder from dividing seventeen by three. As three goes into seventeen five times with two over this means that 17%3 is equal to 2. Next twenty two and five are multiplied together to give 110. Finally the results of these two intermediate calculations are added together to give a final answer.

4 and 5 show how you can modify the first two examples to force JavaScript to do the additions first.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.
Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.