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 operations.
JavaScript permits arithmetic calculations through the use of various arithmetic
operators applied to numeric variables and literal values. The following table
lists and describes the common arithmetic operators.
Operator |
Action |
+ |
Adds two numbers together |
- |
Subtracts one number from another or changes a number to its negative |
* |
Multiplies two numbers together |
/ |
Divides one number by another |
% |
Produces the remainder after dividing one number by another |
Figure 2-9. JavaScript arithmetic operators.
Addition
JavaScript can add together two or more numeric variables and/or numeric constants by
combining them in an arithmetic expression with the arithmetic operator for addition
( + ). The result derived from evaluating an expression can be
assigned to a variable for temporary memory storage.
The following statements declare variables A and B
and assign them numeric values; variable Sum is declared for
storing the result of evaluating the arithmetic expression that adds these two variables.
Additional examples of addition operations using variables and literal numeric values are
shown.
var A = 20;
var B = 10;
var Sum = A + B;
var Sum1 = 1 + 2;
var Sum2 = A + 2 + B + 1;
var Sum3 = Sum1 + Sum2;
The addition operation is illustrated by the following script that you can step through by
clicking the radio buttons.
Figure 2-10. Performing addition.
Subtraction
The subtraction operator ( - ) is used in the same fashion as the
addition operator. Variables and/or literal numeric values are combined with the operator to
subtract values in an expression, the result of which can be assigned to a variable.
var A = 20;
var B = 10;
var Difference = A - B;
var Difference1 = 2 - 1;
var Difference2 = A - 3.5 - B;
var Result = Difference1 - Difference2;
Of course, you can combine addition and subtraction in the same arithmetic expression. These
operations are carried out in the order in which the expression is evaluated from left to right.
The subtraction operation is illustrated by the following script that you can step through by
clicking the radio buttons.
Figure 2-11. Performing subtraction.
Multiplication
Multiplication between numeric variables and/or literal values is accomplished with the
multiplication operator ( * ), examples of which are shown below.
var A = 10;
var B = 20;
var Product = A * B;
var Product1 = 1 * 2;
var Product2 = A * 3.5 * B;
var Result = Product1 * Product2;
The multiplication operation is illustrated by the following script that you can step through by
clicking the radio buttons.
Figure 2-12. Performing multiplication.
Division
Division is accomplished with the divide operator ( / ). The value
preceding the operator (dividend) is divided by the value following the operator (divisor) to
produce the quotient.
var A = 10;
var B = 2;
var Quotient = A / B;
var Quotient1 = 10 / 2;
var Quotient2 = A / 3.5 / B;
var Result = Quotient1 / Quotient2;
The division operation is illustrated by the following script that you can step through by
clicking the radio buttons.
Figure 2-13. Performing division.
A special type of division known as Modulus division returns the remainder in a
division operation. In the following example, when 10 is divided by 3, the quotient is 3 and the
remainder is 1.
Figure 2-14. Performing Modulus division.
The Modulus division operation can be used to determine if one number is equally divisible
by a second number. If the remainder is 0, then the quotient is a whole number. In other cases,
Modulus division can be used to produce a fractional remainder rather than a decimal number.
In the above example, the quotient can be expressed as 3 1/3 rather than 3.333.
Operator Precedence
When an arithmetic expression is evaluated, there is a given order in which the 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 the
expression. This order has important impact on whether or not you get the results expected.
Consider the following declarations and assignments.
var X = 5;
var Y = 3;
var Z = 2;
If you used the arithmetic expression,
var Answer = X - Y * Z;
then the resulting answer would be -1. First, Y
is multiplied by Z to get 6; then
6 is subtracted from 5 to get the answer -1. Suppose,
however, that you really intended to first subtract Y from
X and then multiply by Z to produce the answer
4. The above expression will not work to produce this result
because multiplication takes precedence over subtraction and is performed first, even though
it is the last operation in the expression.
Often, therefore, you need to override operator precedence and explicitly control the
order of evaluation of an expression. This is done by using parentheses ( )
to govern the sequence in which arithmetic operations are carried out. In the above example,
you would use the statement
var Answer = (X - Y) * Z;
to produce your expected results. A good general rule to follow when composing arithmetic
expressions is always to override operator precedence. Use parentheses to explicitly control the
order in which arithmetic operators are evaluated. As in normal arithmetic computations, evaluation
of expressions takes place from the inner-most to the outer-most sets of parentheses.
Other Arithmetic Operators
Other specialized arithmetic operators permit a variable to be used in the calculation of its
replacement value. In other words, you can add to or subtract from a variable (or perform other
arithmetic operations on the variable), and put the resulting value back into the variable.
The following table gives these additional assignment operators which combine computation and
assignment in the same operator.
Operator |
Action |
++ |
X++ The equivalent of X = X + 1; add
1 to X, replacing the value of X |
-- |
X-- The equivalent of X = X - 1; subtract
1 from X, replacing the value of X |
+= |
X += Y The equivalent of X = X + Y; add
Y to X, replacing the value of X |
-= |
X -= Y The equivalent of X = X - Y; subtract
Y from X, replacing the value of X |
*= |
X *= Y
The equivalent of X = X * Y; multiply Y by X,
replacing the value of X |
/= |
X /= Y The equivalent of X = X / Y; divide
X by Y, replacing the value of
X |
Figure 2-15. Operators to perform arithmetic and reassignment to variables.
For example, it is common programming practice to increment or decrement a variable by 1 using the
following statement constructions.
Counter = Counter + 1;
Counter = Counter - 1;
In the first instance, 1 is added to the current contents of variable Counter
and the sum is reassigned to the variable, increasing the value of Counter
by 1. In the second case, the value of Counter is decreased by
1.
Since these are common arithmetic operations, JavaScript provides special arithmetic
operators to automatically increment or decrement a variable without having to compose the kinds
of calculations and assignments shown above. The operator "++" adds
1 to a variable and the operator "--" subtracts 1 from a variable
using expressions in the formats,
Counter ++;
Counter --;
You can use either statement type, however, the latter is easier to write, makes more obvious
the purpose of the statement, and shows up often in other types of JavaScript statements where
variables are incremented or decremented by 1.
Similar types of operators are available for adding and subtracting a second variable, or
multiplying and dividing by a second variable, and reassigning the results to a variable.
For example, if the following declarations are made,
var X = 20;
var Y = 10;
then the expression
X += Y; results in the value X = 30 (Y is
added to X)
X -= Y; results in the value X = 10 (Y is
subtracted from X)
X *= Y; results in the value X = 200 (X is
multiplied by Y)
X /= Y; results in the value X = 2 (X is
divided by Y)
Basic Script Output
You know enough now to begin writing scripts to perform arithmetic operations. The problem is,
you have no way of seeing the results of your processing; they remain hidden inside your scripts.
Later, you are introduced to several different methods to display the results of script processing.
For the time being, a quick and easy way to display script output is with the
alert() method. This is a method of the DOM window object and is
covered more formally later; for now, you can use it for a quick peek at processing results.
alert(variable|expression);
Figure 2-16. Basic format for alert() method.
In its simplest form, the alert() method encloses a variable inside
its parentheses. When this method is called, the value of the variable is displayed in a pop-up
message box. For example, below is a script to perform arithmetic and display the answer in this
pop-up window.
function DoArithmetic() {
var X = 10;
var Y = 20;
var Z = 30;
var Answer = (X + (Y / Z)) / 3.5;
alert(Answer);
}
Listing 2-5. Code to use the alert() method.
The statement alert(Answer) displays the value of variable
Answer. The message box remains on screen until the user clicks
its "OK" button to close the window and return to the Web page.
As mentioned, you are introduced later to several other ways to display the results of script
processing, some by integrating the output within the Web page itself rather than displaying it
in an external message box. For the time being, though, the alert()
method is a handy way to view processing results.
Formatting Numbers
By default, number displays are carried to their decimal capacity. In the previous two examples,
the computations produce the output 3.0476190476190474, with
decimal precision carried to 16 positions. You may wish to have greater control over display
precision.
The JavaScript toFixed(n) method permits number
formatting rounded to n number of decimal positions. This method
can be applied to literal values, variables, or arithmetic expressions by appending it to these
values or computations.
value.toFixed(n)
variable.toFixed(n)
(expression).toFixed(n)
Figure 2-17. Formats to apply the toFixed() method.
Numbers are rounded to the given number of decimal digits. If there is not a sufficient number
of significant (non-zero) digits to display, the number is padded with trailing zeros to the
specified length. When applying the method to an arithmetic expression, it is necessary to
enclose the expression in parentheses so that the method is applied to the full expression.
The following is a rewrite of the script shown above in Listing 2-5. By applying the
toFixed(2) method to the answer, it is displayed as
3.05, rounded to two decimal positions.
function DoArithmetic() {
var X = 10;
var Y = 20;
var Z = 30;
var Answer = (X + (Y / Z)) / 3.5;
alert(Answer.toFixed(2));
}
JavaScript does not supply formatting methods for other standard ways of displaying numbers.
For instance, you cannot automatically display comma separators for numbers over 1,000, nor can
you automatically insert dollar signs in currency values. The latter can be done through string
methods introduced later; the former, however, requires non-trivial programming.
Basic Script Input
In order to make Web pages responsive to users, there also must be ways through which data values
can be input into scripts, rather than simply declaring them as hard-coded values within the script
itself. Most Web page processing, in fact, is based on data supplied by users. Later, you are
introduced to these input methods to round out the input and output techniques to capture user
data for processing and to present output results.
In the meantime, the prompt() method can be used for simple
data input. Like the alert() method, prompt()
is a method of the window object. It is covered in greater detail
later.
variable = prompt("prompt string", "initial value");
Figure 2-18. Basic format for prompt() method.
The prompt() method displays a pop-up window enclosing a text box for
data entry. An "OK" button is displayed to submit the entered value to a script; a "Cancel" button
cancels the input. The "prompt string" is a label to prompt the
user as to the type of input being solicited; the "initial value"
can be used to pre-enter data into the text box, either as a default value or as an example of the
type of input being solicited. The prompt() method is assigned to a
variable to store the entered value.
In its simplest format, the prompt() method works as shown in the
following script. The pop-up box asks the user to enter a name. Then the
alert() method displays this entered value.
function Get_Name() {
var Name = prompt("Enter your name:", "");
alert(Name);
}
The string "Enter your name:" is used as the prompt; a null value
("") is coded as the initial value of the text box so that no pre-entered
data appears. The prompt() method is assigned to variable
Name where the entered data is stored.
When the prompt() method is encounted in a script, the pop-up
window is displayed and the script waits until the user clicks the "OK" or "Cancel" button. At
that point the value entered into the text box is assigned to variable Name,
and the script continues. In this example, variable Name is then displayed
in an alert message, simply echoing the entered value back to the user.
Any number of prompt boxes can be displayed from a script. In the following example, two
boxes serve for input of two numbers which are multiplied together.
function Multiply() {
var No1 = prompt("Enter the first number:", "");
var No2 = prompt("Enter the second number:", "");
var Product = No1 * No2;
alert(Product);
}
If you do not enter valid numbers into the text boxes, the alert()
method displays "NaN", shorthand for "not a number." Later, you will learn more elegant ways
to deal with invalid user input.
Although the alert() and prompt() methods
are relatively crude methods for script output and input, they can serve as a starter kit in making
scripts responsive to user needs.