1/7 LOOPS
Loops
One of a computer’s greatest abilities is to repeat a task multiple times. Loops let us tell the computer to loop over a block of code so that we don’t have to write out the same process over and over.
Loops are especially useful when we have an array where we’d like to do something to each of its items, like logging each item to the console.
There are two kinds of loops we will learn in this lesson:
- for loops, which let us loop a block of code a known amount of times.
- while loops, which let us loop a block of code an unknown amount of times.
Instructions
- What do you think will happen when we execute the code in the text editor? When you think you know, run the code and see what happens!
2/7 LOOPS
Looping Manually
Before we jump into writing a loop, let’s write the output of a loop, so that we can better understand the benefits of writing them.
Instructions
- Write an array and set it equal to a variable named vacationSpots. Inside of this array, list three places you’d like to visit.
- Next, console.log() each item in vacationSpots on a separate line. To do this, list out each item using property access.
Nice work! That wasn’t too hard, but imagine if our vacation list had 100 places on it. Logging each item to the console by hand would be an extremely tedious task!
Let’s make this more efficient with a for loop.
3/7 LOOPS
for Loops, Backwards
If we can make a for loop run forwards through an array, can we make it run backward through one? Of course!
We can make our loop run backward by modifying the start, stop, and iterator conditions.
To do this, we’ll need to edit the code between the for loop’s parentheses:
The start condition should set vacationSpotIndex to the length of the array.
The loop should stop running when vacationSpotIndex is less than 0.
The iterator should subtract 1 each time, which is the purpose of vacationSpotIndex–.
Instructions
- We need to make three changes to our for loop:
Edit the start condition to set vacationSpotIndex equal to the length of the vacationSpots array.
Then, set the stop condition to when vacationSpotIndex is greater than or equal to 0.
Finally, change vacationSpotIndex++ to vacationSpotIndex– to subtract 1 from the iterator variable each loop.
for (let vacationSpotIndex = vacationSpots.length; vacationSpotIndex >= 0; vacationSpotIndex–) { . . . }
- Nice work! Except we printed I would love to visit undefined.
This happened because the length of vacationSpots is 3 so the loop attempted to print vacationSpots[3] which does not exist.
Because arrays start counting at 0, the start condition needs to be the length of the vacationSpots array minus
4/7 LOOPS
Nested for Loops
Let’s say that you and a friend would like to go on vacation together. You’ve both made arrays of your favorite places and you want to compare to see if any of them match. This is a job for loops!
The big idea is that we can run a for loop inside another for loop to compare the items in two arrays.
Every time the outer for loop runs once, the inner for loop will run completely.
These are called nested for loops and we can use them to check to see if any of your vacation spots match your friend’s spots.
See the example below for proper formatting of nested for loops.
for (let i = 0; i < myArray.length; i++) {
for (let j = 0; j < yourArray.length; j++) {
//Code To Run
}
}
Note that in the example above, we used i and j as the iterator variables to make the structure of the code easier to see, but it is a better practice to use descriptive variable names.
Instructions
- We are going to write this program from scratch. Start out by writing a variable named myPlaces and set it equal to an array with three places you’d like to visit.
- Now, make another variable named friendPlaces and set it equal to an array with three places a friend might like to visit.
Make sure that at least one of the places is the same as in your myPlaces array.
- Write a for loop that iterates through each item in myPlaces and logs out each place.
Use myPlacesIndex as the iterator variable.
for loops follow this pattern:
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
- You logged all of your places!
Inside of the existing for loop’s block, below the console.log() statement, write another for loop that loops over friendPlaces. This time, rather than using the myPlacesIndex as the variable name, use friendPlacesIndex. Doing so will prevent us from overwriting any variables. Log each of your friend’s places to the console.
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
for (let j = 0; j < yourArray.length; j++) {
console.log(yourArray[j]);
}
}
- Look what printed to the console. Your first place printed, then all three of your friend’s. Then your second place, then your friend’s places again. Finally, your third place printed and all three of your friend’s places printed a final time.
This is because the inner for loop runs completely every time the outer for loop runs once.
The purpose of the program is to see what you and your friend have in common. Let’s utilize the === comparison with an if statement.
Delete the two console.log() statements you wrote in the previous steps.
Inside the second for loop’s block, write an if statement that checks if myPlaces[myPlacesIndex] is equal to friendPlaces[friendPlacesIndex]. If it is, log to the console the place you have in common.
5/7 LOOPS
while Loops
Awesome job! for loops are great, but they have a limitation: you have to know how many times you want the loop to run. What if you want a loop to execute an unknown or variable number of times instead?
For example, if we have a deck of cards and we want to flip cards (loop a card flipping function) until we get a Spade, how could we write that in JavaScript?
That’s the purpose of the while loop. It looks similar to a for loop. See the example below.
while (condition) {
// code block that loops until condition is false
}
- The loop begins with the keyword while.
- Inside the parentheses, we write a condition. As long as the condition evaluates to true, the block of code will loop.
- Inside the code block, we can write any code we’d like to loop.
Instructions
- Below the array cards, create a variable named currentCard and set it equal to ‘Spade’.
This variable will hold the name of the card we just flipped. We are using ‘Spade’ as the first card.
- Create a while loop. The condition should check if the currentCard is NOT a ‘Spade’.
- In the block of the while loop that you wrote in the previous step, log the value of currentCard to the console. Because the while loop only runs if the card is NOT a Spade, the value of currentCard will only be logged to the console if it is not ‘Spade’.
Below the console.log() statement, add this code:
currentCard = cards[Math.floor(Math.random() * 4)];
This code will generate a random number between 0 and 3, the range of indices of the cards array, and reassign currentCard to a new card from that array.
- Outside the while loop, on the last line of the program, use console.log() to log that the program found a spade.
Change the currentCard that you set to ‘Spade’ in the first step to ‘Heart’ so that the program will run.
Run the code a few times to see the output changing. You can see the while loop guessing a card, then seeing if it is a Spade, over and over, until it finds one.
6/7 LOOPS
Infinite Loops
Loops are a useful tool for improving the functionality of our programs. However, loops can also cause us problems if we aren’t careful.
Both for loops and while loops need explicit instructions on when to terminate. Infinite loops are more common in while loops because they don’t have an iterator built into their syntax. When writing a while loop, be sure to write the code that will guarantee the condition will eventually be met.
for loops require a start condition, a stop condition, and an iterator. The iterator should bring the loop from the start condition to the stop condition.
for (let i = 0; i < array.length; i–) {
//some code
}
- The loop begins with i = 0.
- After one iteration through the loop, i is equal to -1. This is because i begins at 0 and 1 is subtracted from i each loop.
Do you see the problem? i is decreasing each time. It will never equal the length of the array. This code will execute forever.
for (let i = 0; i < array.length; i++) {
//some code
}
We changed the iterator to i++ which means i will eventually equal the length of the array. We have eliminated the infinite loop!
Note: While completing this exercise, you may run into an infinite loop if you do not find the correct answer. If that happens, you may need to refresh the page.
Instructions
- In the for loop, one of the three conditions is incorrect and will cause the code to execute forever. Change one of these three conditions to eliminate this infinite loop.
Change the incrementer so that it counts down instead of up. - In the while loop, the code block should execute as long as the length of the array is greater than 3. However, the length of the thingsToDo array is greater than 3 and we aren’t executing any code to change that.
Uncomment the code for the while loop by deleting all of the slashes (//).
On line 9, use an array method to remove an element from the thingsToDo array each time the block executes.
7/7 LOOPS
Review: Loops
Great job! In this lesson, we learned how to write less repetitive code with loops.
- for loops allow us to repeat a block of code a known amount of times.
- We can use a for loop inside another for loop to compare two lists.
- while loops are for looping over a code block an unknown amount of times.
- Infinite loops occur when stop conditions are never met.
Sé el primero en comentar