More on Loops using while, do while, and for

CS133JS Beginning Programming: JavaScript

Topics by Week 
1. Intro to JavaScript programming6. Arrays
2. Functions, Operators and Expressions7. Objects
3. Conditional Statements: if and switch8. Methods
4. Repetition: while, do while, and for9. DOM
5. Midterm Check-Point10. Term project
11. Final 

 

Table of Contents


Introduction

Announcements

Q and A

 


Review

Repetition Using while

This is a pretest loop The variables used in the loop condition must be declared outside the loop.

Repetition Using do while

This is a post-test loop The variables used in the loop condition must be declared outside the loop in this one too.

Repetition Using for

This is a loop with a built-in counter The loop counter's scope is local to the loop.

 


 

Interrupting Loop Iteration

We can interrupt the normal flow of execution in a loop using break, or continue, but these are rarely needed. You can almost always control the execution of your loop by choosing the right kind of loop and the right loop condition. These are only used as a lost resort, because they make your code more complex.

break

This causes execution to jump out of the loop.

Example of a for loop that uses break

 

continue

This "short-circuits" the execution so it jumps over the rest of the statements in the loop.

Example of a for loop that uses continue

 


Nested Loops

We can put one loop inside another.

Example: a while loop nested in a do while loop

 

Example: nested for loops

Note: The console needs to be wide enough to show the rows without wrapping.

Q: What would you need to change to use this code in a web page1?

 

Debugging

Best Practices

 


Reference

Mozilla Developer Network

Loops and Iteration

The Firefox JavaScript Debugger

 

Creative Commons License Beginning JavaScript Lecture Notes by Brian Bird, 2018, revised are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

 


1 You can't use a tab character in an HTML page (unless it's inside a <pre> element. But you can use a series of &nbsp. At the end of each row you need to use <br> In place of `console.log(), you will use document.write().