Previous Contents Next
3. Operators and Expressions

Arithmetic Operations

One of the fundamental ways you can derive information from numeric data is to manipulate them arithmetically--to process the data through addition, subtraction, multiplication, division, and combinations of these computations. JavaScript permits arithmetic computations through the use of various arithmetic operators applied to the numeric variables and literals in your program.

The following table lists and describes these arithmetic operators:

Operator Action
+
Adds two values together.
-
Subtracts one value from another or changes a value to its negative.
*
Multiplies two values together.
/
Divides one value by another.
++
Increments the value of a variable by 1.
--
Decrements the value of a variable by 1.

 

Addition

JavaScript can add together two or more numeric variables and/or literals by relating them with the arithmetic operator for addition (+). The result derived from evaluating this arithmetic expression is assigned to a variable. For example, consider the following simple script:

var Sum = 0
var X = 100
var Y = 125
Sum = X + Y

First, a variable named Sum is declared and initialized to 0 in order to set aside a storage area where the result of a calculation will be placed. Second, a variable named X is declared and initialized with the numeric value of 100. Third, variable Y is declared and initialized with the value of 125. Fourth, the expression X + Y is evaluated and the result is placed in variable Sum, replacing the initial value. At the close of the script, variable Sum contains the value 225. You can check this by executing the following script:

Sum
X
Y
var Sum = 0
var X = 100
var Y = 125
Sum = X + Y

Incidentally, it is not necessary in the above example to declare and initialize the variable sum. Variables can be created "on the fly" simply by assigning something to them. So, the script would work exactly the same by using the three statements:

var X = 100
var Y = 125
Sum = X + Y

In this case, variable sum is created by assigning the result of the expression to it. Usually, however, it is a good idea to declare and initialize all variables at the beginning of the script so that you have complete, prior documentation of their existence and proposed use.

You can combine literals with variables and have more than two items added together in an expression:

Sum = X + Y + 10.5
Sales_Total = Item1 + Item2 + Item3 + 9.25
Test_Total = Section1_Score + Section2_Score + Section3_Score + 10

There is no real limit on the number of numeric variables and/or literals that can be added together in a single expression.

Subtraction

The subtraction operator (-) works in the same fashion as the addition operator. Variables and literals are combined with the operator to subtract values in an expression, the result of which is assigned to a variable. For example, in the script

var Difference = 0
var X = 125
var Y = 100
Difference = X - Y

the expression X - Y in the last statement produces the value 25, which is stored in the variable named Difference.

Difference
X
Y
var Difference = 0
var X = 125
var Y = 100
Difference = X - Y
Again, you can combine as many variables and literals as needed to make the computation:

Total = Sales_Amt - Discount_Amt + Shipping_Chrg + Sales_Tax

There is one special use of the subtraction operator. When it alone precedes a variable in an expression, it reverses the sign of the value of the variable. That is, in the script

var Number = 100
Number = - Number

variable Number is changed from its original value of 100 to -100 and placed back into the variable. If its original value were -100, the expression changes it to (+)100.

Multiplication

Multiplication between numeric variables and/or literals is accomplished with the multiplication operator (*). As you can probably guess, if you defined

var Area = 0
var Width = 55
var Length = 25

then you can calculate the area as

Area = Width * Length

Area
Width
Length
var Area = 0
var Width = 55
var Length = 25
Area = Width * Length

Or, if

var Area = 0
var Pi = 3.1416
var Radius = 10

then you can calculate the area of the circle with

Area = Pi * Radius * Radius

Division

Division is accomplished with the divide operator (/). In an expression, the value preceding the operator is divided by the value following the operator. Thus, in the script

var Ratio = 0
var X= 75
var Y = 5
Ratio = X / Y

variable Ratio is assigned the result of dividing variable X by variable Y.

Ratio
X
Y
var Ratio = 0
var X = 75
var Y = 5
Ratio = X / Y

Operator Precedence

When an expression is evaluated, there is a given order in which the arithmetic operations are carried out. This order is called operator precedence. Multiplication and division take precedence (are done first) over addition and subtraction, moving from left to right through an expression. This order has an important impact on whether or not you get the results expected.

Consider the two cases shown below. In both, the same variables are initialized with the same values: X = 5, Y = 3, and Z = 1. The only difference is in the arithmetic expressions that are applied. In the first case: Answer = X * Y - Z; in the second case: Answer = X * (Y - Z). When the two expressions are evaluated, two different answers result, even though the operations are the same.

Answer
X
Y
Z
Answer
X
Y
Z
Answer = X * Y - Z
Answer = X * (Y - Z)
The different answers result from operator precedence. In the first case, multiplication takes place before subtraction. Therefore, the answer is given by first multiplying X * Y and then subtracting Z (resulting in a value of 14). If, however, the computation requires you to first subtract Y - Z, then this expression can't work. You must override operator precedence. This is done in the second case where parentheses are used to govern the order of evaluation (just as they do in all mathematical formulas). Here, the answer is given by first subtracting Y - Z and then multiplying by X (resulting in a value of 10).

The general rule to follow in composing expressions is to ignore operator precedence and use parentheses to control the order of evaluation. In this way you have more control over the computation and are less likely to be surprised by unexpected answers.

Incrementing and Decrementing

Variables to which you assign a value can also be involved in the calculation of that value. That is, you can take the value in a variable, add something to it or subtract something from it, and put the result back into the variable. You do not have to assign the result to an entirely new variable. For instance, it is common programming practice to increment or decrement a variable in the following ways:

Counter = Counter + 1
Counter = Counter - 1

These might appear convoluted but they makes perfect sense. In the first instance, 1 is added to the contents of Counter and the sum is placed back into the variable (effectively increasing the value of Counter by 1). In the second case, the contents of Counter has 1 subtracted from it; the result is placed back into Counter (effectively reducing the value of Counter by 1).

Many languages, JavaScript included, now contain arithmetic operators to automatically increment or decrement a variable without having to use these kinds of assignments. These operators work to increment a variable by 1 (++) and to decrement a variable by 1 (--). So, if you have a variable named Counter and wish to add 1 to it, you use the expression

Counter++

(without the "=" assignment operator) which has the same effect as using the expression Counter = Counter + 1. Likewise, if you need to decrease the value of the variable by 1, you can use the decrement operator

Counter--

which has the same effect as Counter = Counter - 1. These uses of increment and decrement operators come into regular play in a later topic on program loops.

Other Assignment Operators

Just to round out the discussion of arithmetic operators, the following table gives additional assignment operators besides the "=" sign. These operators combine computation and assignment in the same operator and can be used in place of their equivalents.

Operator Action
+=
(x += y) The equivalent of x = x + y. Takes the value in the variable on the left, adds it to another value, and places the result back into the variable on the left.
-=
(x -= y) The equivalent of x = x - y. Takes the value in the variable on the left, subtracts another value from it, and places the result back into the variable on the left.
*=
(x *= y) The equivalent of x = x * y. Takes the value in the variable on the left, multiplies it by another value, and places the result back into the variable on the left.
/=
(x /= y) The equivalent of x = x / y. Takes the value in the variable on the left, divides it by another value, and places the result back into the variable on the left.

 

String Operations

The previous discussion has covered operations perform on numeric data. There is one operation that you can perform on string data. Recall, a text string is a sequence of alphabetic, numeric, and other characters--enclosed in quotes--and treated as a simple block of text. Of course, you cannot perform arithmetic on text strings, but you can concatenate strings, which means to link two or more strings together. This is accomplished with the concatenation operator (+), which looks suspiciously like an addition operator, but it's not when used with string data.

Assume you have the following variables declared:

var FirstName = "Gloria"
var MiddleInitial = "J."
var LastName = "Green"

and you wish to create a variable, FullName, containing the three variables appended together. You use the concatenate operator to tied them all together:

FullName = FirstName + " " + MiddleInitial + " " + LastName

as you can see in the following script:

FullName
FirstName
MiddleInitial
LastName
var FirstName = "Gloria"
var MiddleInitial = "J."
var LastName = "Green"
FullName = FirstName + " " + MiddleInitial + " " + LastName
Note in the concatenation statement that literal blank spaces (" ") are added between the names to keep them from running on to one another.

You should be aware that numerals can appear within strings if they are not intended for arithmetic operations. For example, you can define

var Month = "7"
var Day = "15"
var Year = "1997"

However, if defined as strings (in quotes) they are treated as strings with the + operator, and not as numbers. Check the differences in the follow two scripts, noting that in the first case the month/day/year values are initialized as strings and are concatenated and in the second case they are initialized as numbers and are added:

Result
Month
Day
Year
Result
Month
Day
Year
var Month = "7"
var Day = "15"
var Year = "1997"
Result = Month + Day + Year
var Month = 7
var Day = 15
var Year = 1997
Result = Month + Day + Year

We have just scratched the surface on arithmetic and string operations. There are a number of built-in operations that can be used to increase the range of processing tasks on these data. These topics will be taken up later. However, you should have the knowhow and the design models to follow to start writing simple scripts using arithmetic and string operations.

The previous examples generated input data by assigning literal values to variables, either within the script or by clicking on buttons. To make your scripts useful, however, you need to provide for user input; that is, users need to be able to enter their own data. Plus, following processing, your scripts need to output the results for users to view. User input and output is introduced in the next topic.


Previous Contents Next