HTML and CSS Reference
In-Depth Information
TABLE 14.1
JavaScript Operators and Expressions
Operator
Example
Description
Adds the two numeric values; the result is
10.
+
5 + 5
Combines the two string values; the result
is JavaScript.
+
“Java” + “Script”
Subtracts the second value from the first;
the result is 5.
-
10 - 5
Multiplies the two values; the result is 25.
*
5 * 5
Divides the value on the left by the value
on the right; the result is 5.
/
25 / 5
Obtains the modulus of 26 when it's
divided by 5. (Note: A modulus is a func-
tion that returns the remainder.) The result
is 1.
%
26 % 5
Increments the value by 1; the result is 6.
++
5++
Decrements the value by 1; the result is 5.
6—
There are many other operators, too. All the examples here used literal values in the
expressions, but there are other options, too. You can use values returned by methods in
expressions if you choose, as in the following example:
<script type=”text/javascript”>
document.write(Math.sqrt(25) - Math.sqrt(16));
</script>
This example uses the Math object, another object built in to JavaScript. It provides a
number of methods that perform a variety of mathematical operations so that you don't
have to write the code to perform them yourself. Math.sqrt() is a method that returns
the square root of a number. In this case, I subtracted the square root of 16 from the
square root of 25 and passed the result to document.write() .
Variables
Thus far, I've been manipulating values and printing them directly to the page. The next
fundamental building block of writing scripts is temporary storage of those values so that
they can be reused. Like all programming languages, JavaScript supports the use of vari-
ables. A variable is a user-defined container that can hold a number, text, or an object.
Creating a variables and retrieving their values is simple:
 
 
Search WWH ::




Custom Search