|
10 Conditional flow
8 different ways to affect program flow
if
..
else
,
switch
,
for
..next,
do
..
while
,
while
,
for
..
in
,
with
,
?
if
---------------------------------------------------
if
(condition)
{
Block
}
//block is one or more lines of code to execute if condition is true
or, more general version
:
if
(condition)
{
Block
}
else
{
Block
}
switch
---------------------------------------------
switch
(expression)
{
case
"dog"
:
//note use of colon at end of line
{
Block
}
break
;
//note use of semicolon at end of line
case
"cat"
:
{
Block
}
break
;
default
:
{
Block
}
}
for
..next
---------------------------------------------
for
(i
=
0; i
<
10; i
++
)
// for (initialize; condition; adjust)
{
Block
}
// statements
do
..
while
---------------------------------------------
do
{
Block
}
while
(expression)
while
--------------------------------------------------
while
(expression)
{
Block
}
for
..
in
------------------------------------------------
for
(myvariable
in
object)
//cycle through all enumerated properties of the object (elements of Array object)
{
Block
}
//order of properites is unknown
//methods and some properties are not enumerated
Example of
for
:
for
(myvar
in
wine1)
{
record
+=
1
}
document.write (record)
with
------------------------------------------------
with
(object)
{
Block
}
//properties and methods of object can leave off the repetitive portion (shown in parentheses)
?
--------------------------------------------------
result
=
(condition)
?
(
if
true
)
:
(
if
false
) ;
//conditional operator ?
Additional options
-----------------------
use
'break'
to drop out of loop
use
'continue'
to drop out of current iteration of the loop
|