The values we have stored in our variables aren’t going to be much use to us unless we can manipulate them in calculations.
var theSum = 4 + 3;
As you’ll have guessed, after this statement has been executed the variable theSum will contain a value of 7. We can use variable names in our operations too:
var productCount = 2; var subtotal = 14.98; var shipping = 2.75; var total = subtotal + shipping;
subtotal = total shipping; var salesTax = total * 0.15; var productPrice = subtotal / productCount;
var itemsPerBox = 12; var itemsToBeBoxed = 40; var itemsInLastBox = itemsToBeBoxed % itemsPerBox;
In this example, the variable itemsInLastBox would contain the number 4 after the last statement completes.
is equivalent to the statement
productCount = productCount + 1;
is just the same as
items = items 1;
var average = a + b + c / 3;
If, as the variable’s name implies, you’re trying to calculate an average, this would not give the desired result; the division operation would be carried out on c before adding the values of a and b to the result. To calculate the average correctly, we would have to add parentheses to our statement, like this:
var average = (a + b + c) / 3;
If you have doubts about the precedence rules, I would recommend that you always use parentheses liberally. There is no cost to doing so, it makes your code easier to read (both for you and for anyone else who later has to edit or decipher it), and it ensures that precedence issues don’t spoil your calculations.
Using the + Operator with Strings
var firstname = “John”; var surname = “Doe”; var fullname = firstname + “ “ + surname; // the variable fullname now contains the value “John Doe”
var name = “David”; var age = 45; alert(name + age);
Figure 2.2 shows the result of using the + operator on a string and a numeric value.
Figure 2.2 Concatenating a string and a numeric value