HTML and CSS Reference
In-Depth Information
A common use of the += operator is to concatenate text strings to create a single, long
text string. This is useful in situations where a text string that covers several lines might be
difficult to store in a variable using a single statement. You can use the += operator to do
this, as follows:
Always type += for the
addition assignment
operator; do not insert a
space between the two
symbols or JavaScript will
report a syntax error.
quote = “To be or not to be: “;
quote += “That is the question. “;
quote += “Whether 'tis nobler in the mind to suffer “;
quote += “the slings and arrows of outrageous fortune, “;
quote += “Or to take arms against a sea of troubles”;
quote += “And by opposing end them.”;
...
Continuing in this fashion, the quote variable eventually contains the complete text of
Hamlet's soliloquy by using a series of short, simple expressions rather than one long and
cumbersome expression. This technique is often used to store long text strings within a
variable. Assignment operators are described in Figure 11-15.
Figure 11-15
assignment operators
Operator
Description
Example
Equivalent To
=
Assigns the value of the expression on the right to the
expression on the left
x = y
x = y
+=
Adds two expressions and assigns the value to a
variable
x += y
x = x + y
-=
Subtracts the expression on the right from the expres-
sion on the left and assigns the value to a variable
x -= y
x = x - y
*=
Multiplies two expressions and assigns the value to a
variable
x *= y
x = x * y
%=
Calculates the remainder from dividing the expression
on the left by the expression on the right and assigns
the value to a variable
x %= y
x = x % y
After you master the syntax, you can use assignment operators to create efficient and
compact expressions. New JavaScript programmers might prefer to use the longer form
for such expressions. However, experienced JavaScript programmers make substantial
use of assignment operators to reduce program size.
Calculating the Days Left in the Year
You'll use operators and Date objects to create a function that calculates the number of
days remaining in the year. This function, which you'll name calcDays() , will have a
single parameter named currentDate that contains a Date object for the current date
and time. The following code shows the basic structure of the function:
function calcDays(currentDate) {
// create a Date object for January 1 of the next year
// calculate the difference between currentDate and January 1
}
Because you want the calcDays() function to be available to other pages of the Web
site, you'll add this function structure to the functions.js file.
 
Search WWH ::




Custom Search