2. Changes in Direction
●
In the previous video we allowed our program to
change flow to one of many different program
blocks
●
But that is not the only direction change we may
want. It is often desireable to repeatedly execute
the same block
●
Looking for some value in a list
●
Sending a group email
●
In other words we want to loop
3. The While loop
●
At the top of the loop the condition is checked
●
If the condition is met then execute code block
●
Loop will continue until condition not met.
while (conditional expression) {
//Do some stuff
}
●
Be sure that eventually the condition will not be
met otherwise you get an infinite loop;
4. The Do loop
●
At the bottom of the loop condition is checked
●
Assures the code block will be executed at least
once
●
Loop continues until condition false
do {
//code to execute goes here
} while (conditional expression);
5. Basic For loop
●
Executes the loop a number of times
●
Has three statements
●
First excutes before the loop is executed
– Usually used for initialization
●
Second conditional expression
– Code executes if true
●
Third
– Executes after the code block before the next
iteration
7. For looping through
properties
●
Used to examine properties of an object
●
Important to filter as all properties examined
even those inherited from parent and its
parent....
for (variable in Object) {
if ( Object.hasOwnProperty(variable) {
//code to execute
}
}
8. Cutting the loop
●
break
●
Halts code execution in the loop
– Stop further execution of code block and exit the
loop
●
continue
●
Halts execution of the rest of the code block
●
Continues next iteration
9. Summary
●
Iteration is another word for looping
●
While loops check for conditional at the top of
the loop
●
Be wary of the infinite loop
●
Do loops check conditional at bottom of the loop
●
Basic for loops allow loops to be controlled by
number of executions
●
For in loops will check properties of Objects and
Arrays
●
Be sure to use hasOwnProperty method.