Page 18 - LoudOffice_Guide-to-HTML_Part-II_Advanced.PDF
P. 18
continue if public var
default implements return void
delete import short while
do in static with
double instanceof super
Variables and Data Types
Variables store and retrieve data, also known as "values". A variable can refer to a value
which changes or remains constant. Variables are referred to by name, although the name
you give them must conform to certain rules. A JavaScript identifier, or name, must start
with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Because
JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and
the characters "a" through "z" (lowercase). Typically, variable names are chosen to be
meaningful regarding the value they hold. For example, a good variable name for containing
the total price of goods orders would be t o t a l .
Scope
When you assign a new variable to an initial value, you must consider the issue of scope. A
variable may be scoped as either global or local. A global variable may be accessed from
any JavaScript on the page. A local variable may only be accessed from within the function
in which it was assigned. One purpose of using scope is to prevent collisions between
variables of the same name; for instance, you may wish to use a variable named "Total" in
one function which has a different value and meaning than another variable named "Total"
in a separate function. In that case, both variables should have local scope. Commonly, you
create a new global variable by simply assigning it a value:
n e w V a r i a b l e = 5 ;
However, if you are coding within a function and you want to create a local variable which
only scopes within that function you must declare the new variable using the v a r
statement:
f u n c t i o n n e w F u n c t i o n ( ) {
v a r l o o p = 1 ;
t o t a l = 0 ;
. . . a d d i t i o n a l s t a t e m e n t s . . .
}
In the example above, the variable l o o p will be local to n e w F u n c t i o n ( ) , while t o t a l will
be global to the entire page.
LoudOffice.com Guide to HTML – Part II Page 18