JavaScript iteration

10

Click here to load reader

description

This is the slides for the YouTube video i did on this subject

Transcript of JavaScript iteration

Page 1: JavaScript iteration

JavaScript Iterations

Charles Russell

Bennu Bird Media

Page 2: JavaScript iteration

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

Page 3: JavaScript iteration

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;

Page 4: JavaScript iteration

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);

Page 5: JavaScript iteration

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

Page 6: JavaScript iteration

Basic For Syntax

for (init ; conditional exp; prepForNext) {

//do some stuff

}

Page 7: JavaScript iteration

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

}

}

Page 8: JavaScript iteration

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

Page 9: JavaScript 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.

Page 10: JavaScript iteration

Next: Live Code