JavaScript iteration
Click here to load reader
-
Upload
charles-russell -
Category
Internet
-
view
124 -
download
2
description
Transcript of JavaScript iteration
JavaScript Iterations
Charles Russell
Bennu Bird Media
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
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;
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);
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
Basic For Syntax
for (init ; conditional exp; prepForNext) {
//do some stuff
}
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
}
}
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
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.
Next: Live Code