JavaScript Variables and Operators

Assignment Operators

We have already seen a few simple examples of assignment operators when we looked at assigning values to variables when we first define them. The same assignment operator works for assigning a replacement value to a variable. Here are some examples.

1 var price = cost + profit;
2 remains = purchased - eaten;
3 min = count++;

In 1 a new variable price is created. The values in cost and profit are added together and the result of this addition is stored in price. The values in cost and profit are not changed.

2 subtracts eaten from purchased and stores the result in remains.

3 copies the value from count into min. It then adds one to count so that count will be one greater than min after this statement runs.

Where we want to add one number to another and store the result in one of the existing fields rather than a new field JavaScript provides a shorthand notation. The same shorthand notation also exists for each of the other numerical operators.

fruit += apples;
price -= tax;
timeWorked *= days;
pages /= books;
entry %= selection;

The first of these statements has the same result as if we had put fruit = fruit + apples; The difference is that instead of adding fruit and apples together in a temporary field and then moving the result back into fruit the value of apples can be added to fruit directly.

Similarly price -= tax; is equivalent but more efficient than price = price - tax;, timeWorked *= days; is equivalent to timeWorked = timeWorked * days; and so on.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow