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. Repetition9. DOM
5. Midterm10. Review
11. Final 

 

Table of Contents


Introduction

Announcements

Fall 2024

 


Review

Selection Using switch Statements

Control Structures

There are three control structures in programming:

  1. Sequence

  2. Selection

  3. Repetition, which is also called looping.

 


This week's topic: Loops (Repetition)

Loop statements execute a block of code multiple times. There are several types of loops in JavaScript. This week we'll learn how to use:

And some more we'll learn aobut about later:

 

while Loops

The while loop iterates (repeats the code inside it) as long as a condition is true. It checks the loop condition expression at the beginning of the loop, so it called a pretest loop.

Parts of a while loop

Assume we have initialized a variable: let age = 0;

key word conditional expression

   ↓               ↓

Example: input validation

Example: a loop with a counter

If we run this in the console, is there some value we could set count to that would prevent the loop from ever iterating, not even once?

Scope of variables in while loops

Any variable (or variables) used in the loop test condition must be declared outside the loop. In the example above, degrees, is declared outside the loop, so its scope is greater than the body of the loop.

In next example, we add a variable which has a scope of just the loop body.

Example: a loop with a local variable

If we run this in the console, how can we show that count is global and timesTen is local to the loop body?

 

do while Loops

The same as the while loop, but it checks the condition at the end of the loop, so it is a post-test loop.

Note the semicolon at the end of the loop conditionthis is a syntactic detail that's easy to miss!

Example: a loop with a counter

Is there any value of count that would prevent this loop from iterating at least once?

Input Validation with a do while Loop

Example: input validation

Is there any way this loop would not iterate at least once?

This example we validated the range of input. What could it make sense to validate?

for Loops

The for loop is used when you know how many times you want to iterate (go around the loop).

Structure

  initial value condition increment

        ↓         ↓       ↓

 

Example: a loop that shows squares of numbers

Omitting parts of the for loop header

Example: declare the variable outside the loop

Note: you need to leave the semicolon there as a placeholder.

While you can do this, it's not recommended unless you really need your loop counter to be visible in the scope outside your loop.

 

Example: increment the loop counter in the body of the loop

Again, moving the increment expression is something you can do, but it's not recommended since it makes your code more difficult to understand. You would only do this if you really needed to.

 

Solving Problems that Involve Loops

We have looked at several problem solving approaches in the past:

Practice problem:
Assume a person is registering a new password for an account. Write code that prompts the user to enter a password, and keeps prompting until the user enters a password that is at least 8 characters long. When they enter one that is long enough, display a success message.

Writing the Algorithm

You can often come up with an algorithm by thinking about how you would do something without using a computer. For example, if you were checking a person's password yourself, the person would tell you their password and you would keep telling them to try another one until it was long enough.

  1. Give the user instructions for registering a password.

  2. Get a password as input.

  3. Check the length, go to 1 if it's less than 8 characters long.

  4. Display "New password accepted"

The Solution

 

Practice Exercises and Examples

Show everyone how to download the example .html and .js files from a browser by right-clicking on the link in the instructions and selecting "Save as".

These are the same examples that are on Moodle:


Reference

Mozilla Developer Network

Loops and Iteration

JavaScript Tutorial

JavaScript while Loop

JavaScript do...while Loop

JavaScript for Loop

Eloquent JavaScript

Ch. 2, Program StructureThe sections on loops.

 

 

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