while, do while,
and for
CS133JS Beginning Programming: JavaScript
Topics by Week | |
---|---|
1. Intro to JavaScript programming | 6. Arrays |
2. Functions, Operators and Expressions | 7. Objects |
3. Conditional Statements: if and switch | 8. Methods |
4. Repetition | 9. DOM |
5. Midterm | 10. Review |
11. Final |
IntroductionAnnouncementsReviewSelection Using switch
StatementsControl StructuresThis week's topic: Loops (Repetition)while
LoopsScope of variables in while
loopsdo while
LoopsInput Validation with a do while
Loopfor
LoopsOmitting parts of the for
loop headerSolving Problems that Involve LoopsWriting the AlgorithmThe SolutionPractice Exercises and ExamplesReference
Fall 2024
Lab 3 code review due Today
If your lab partner didn't post a beta version for you to review, there is alternative beta code you can review this instead.
Reading quiz closes Thursday.
Lab 3 production version due Thursday.
Midterm next week.
Review lecture notes.
Practice midterm.
You can take the quiz in the classroom at class time, or you can take it in the testing center.
Classroom from 10:00 to 11:50 (normal class time).
Testing center
The testing center is located in the Center Building, Room 311 (upstairs and across from the library).
Thursday, 10/31, 9:00am–7:30pm
Friday, 11/1, 9:00am–5:00pm.
Saturday, 11/2, 10:00am–2:00pm
In both locations:
You aren't allowed to use: help from others, internet searches, AI (like ChatGPT), or any other outside sources.
You will be allowed to refer to one page of notes.
Does anyone have any general questions about anything?
Questions about lab 3 on selection?
switch
Statementsxlet color = prompt("What is a common color for a mouse?");
let response = ""; // comment on answer
let score = 0; // socre for answer
switch (color)
{
case "grey":
case "gray":
response = "Yes!";
score = 10;
break;
case "brown":
case "white":
score = 5;
response = "OK, sometimes";
break;
default:
score = 0;
response = "I don’t think so";
}
console.log("score: " + score + ", comment: " + response);
There are three control structures in programming:
Sequence
Selection
Repetition, which is also called looping.
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:
while
do while
for
And some more we'll learn aobut about later:
for in
(we'll learn about this one after we've learned about arrays).
for of
(we'll learn about this one after we've learned about objects.)
while
LoopsThe 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
↓ ↓
xxxxxxxxxx
while (age <= 0 || age > 125) // loop header
{ // loop body
age = parseInt(prompt("Enter a valid age."));
}
Example: input validation
xxxxxxxxxx
// Re-prompt for input until the user enters it correctly
let degrees = 0;
degrees = parseFloat(prompt("Enter the temperature"));
while(degrees < -100 || degrees > 150) // invalid temperatures
{
alert("Please enter a temperature between -100 and 150");
degrees = parseFloat(prompt("Enter the temperature"));
}
// Do something with the user's input
Example: a loop with a counter
xxxxxxxxxx
// Count to 10
let count = 1;
while(count <= 10)
{
console.log(count);
count += 1;
}
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?
while
loopsAny 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
xxxxxxxxxx
// Count to 10 by ones and to 100 by tens
let count = 1;
while(count <= 10)
{
let timesTen = count * 10;
console.log(count + ", " + timesTen);
count += 1;
}
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
LoopsThe 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 condition—this is a syntactic detail that's easy to miss!
Example: a loop with a counter
xxxxxxxxxx
// Count to 10
let count = 1;
do
{
console.log(count);
count += 1;
} while(count <= 10);
Is there any value of count
that would prevent this loop from iterating at least once?
do while
LoopExample: input validation
xxxxxxxxxx
// Enter input until the user enters it correctly
do
{
alert("Please enter a temperature between -100 and 150")
degrees = prompt("Enter the temperature");
} while(degrees < -100 || degrees > 150); // invalid temperatures
// Do something with the user's input
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
LoopsThe for loop is used when you know how many times you want to iterate (go around the loop).
Structure
initial value condition increment
↓ ↓ ↓
xxxxxxxxxx
for (let i = 1; i <= 10; i++) // loop header
{ // loop body
console.log(i);
}
Example: a loop that shows squares of numbers
xxxxxxxxxx
// Display squares of a series of numbers
for (let i = 0; i < 5; i++)
{
let result = i * i;
console.log(i + " squared = " + result);
}
How many times will the loop execute?
What is the scope of i
?
What is the scope of result
?
What will the final value of i
be?
for
loop headerExample: declare the variable outside the loop
xxxxxxxxxx
// Display squares of a number
let i = 0;
for (; i < 5; i++)
{
let result = i * i;
console.log(i + " squared = " + result);
}
Note: you need to leave the semicolon there as a placeholder.
What is the scope of i
now?
What is the scope of result
?
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
xxxxxxxxxx
// Display squares of a series of numbers
let i = 0;
for (; i < 5;)
{
let result = i * i;
console.log(i + " squared = " + result);
i++;
}
What would happen if you moved the code that increments i
to the beginning of the loop body?
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.
We have looked at several problem solving approaches in the past:
Writing algorithms in English (or pseudo-code)
We will do this again for problems involving loops
Making IPO charts
This is especially helpful for problems involving selection, but not so much for problems involving loops.
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.
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.
Give the user instructions for registering a password.
Get a password as input.
Check the length, go to 1 if it's less than 8 characters long.
Display "New password accepted"
xxxxxxxxxx
let password = "";
do {
password = prompt("Please enter a string with at least 5 characters:");
} while (password.length < 8);
console.log("New password accepted");
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:
Loop Practice. These problems are similar to part 1 of the lab assignment:
CS133JS_Lab04_Part1_Example.html—use this html file with the practice problems or with the solution. After downloading, uncomment the <script>
element linking the .js file you want.
CS133JS_Lab04_Part1_Example_Starter.js —practice problems.
CS133JS_Lab04_Part1_Example.js — solution to the practice problems.
These examples are similar to part 2 of the lab assignment:
Rainfall table - uses a for loop.
Car Seat - uses a while loop for input validation.
Actors and Movies - uses a while loop for validation and a do-while loop to re-run the program.
Additional loop practice problems—Fifteen loop problems, with solutions, that are similar to those in part 1 of the lab assignment.
Mozilla Developer Network
JavaScript Tutorial
Eloquent JavaScript
Ch. 2, Program Structure—The sections on loops.
Beginning JavaScript Lecture Notes by Brian Bird, 2018, revised are licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.