Page 22 - LoudOffice_Guide-to-HTML_Part-II_Advanced.PDF
P. 22
Switch (JavaScript 1.2+)
Commonly known as a "case statement," switch matches an expression with a specified
case, and executes the statements defined for that case. In essence, the switch statement
is a sort of shorthand for combining many implied if statements together.
s w i t c h ( e x p r e s s i o n ) {
c a s e s e l e c t i o n _ o n e :
s t a t e m e n t s ;
b r e a k ;
c a s e s e l e c t i o n _ t w o :
s t a t e m e n t ;
b r e a k ;
. . .
d e f a u l t : s t a t e m e n t ;
}
For
The for loop repeatedly cycles through a block of statements until a test condition is false.
Typically, the number of times a loop is repeated depends on a counter. The JavaScript for
syntax incorporates the counter and its increments:
f o r ( i n i t i a l - s t a t e m e n t ; t e s t ; i n c r e m e n t )
{ s t a t e m e n t s ; }
i.e.
f o r ( i = 0 ; i < 1 0 ; i + + )
{ s t a t e m e n t s ; }
Comments
Despite the fact that comments are purely optional, they can easily be a crucial part of your
program. Comments can explain the action, like a color commentary, which can be a great
help in understanding the code. Whether as a teaching tool or to simply remind yourself
what the code does, comments are best sprinkled liberally throughout a program.
Remember, comments are for humans, so write them that way!
Comments can also be used for debugging -- you can comment "out" sections of code to
prevent them from being executed. In doing so you may learn more about why a certain
problem is occurring in your program.
Because JavaScript must ignore comments, there is an appropriate syntax for demarcating
text as a comment. For single line comments, simply precede the line with two backslashes.
For multi-line comment blocks, begin the comment with / * and close with * / .
/ / A l o n e l y o l ' s i n g l e l i n e c o m m e n t
/ * A d e n s e t h i c k e t o f c o m m e n t a r y , s p a n n i n g m a n y c a p t i v a t i n g
l i n e s o f e x p l a n a t i o n a n d i n t r i g u e . * /
Functions
A function groups together a set of statements under a named subroutine. This allows you
to conveniently "call" the function whenever its action is required. Functions are a
fundamental building block of most JavaScript programs, so you'll become quite familiar
with their use. Before you can call on a function you must first create it. We can break down
the use of functions into two logical categories: defining functions and calling functions.
LoudOffice.com Guide to HTML – Part II Page 22