Loops
In this course, you will learn how to use for and while loops to execute blocks of code multiple times.
StartKey Concepts
Review core concepts you need to learn to master this subject
While Loop
Reverse Loop
Do…While Statement
For Loop
Looping Through Arrays
Break Keyword
Nested For Loop
Loops
While Loop
While Loop
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
The while
loop creates a loop that is executed as long as a specified condition evaluates to true
. The loop will continue to run until the condition evaluates to false
. The condition is specified before the loop, and usually, some variable is incremented or altered in the while
loop body to determine when the loop should stop.
- 2Before we write our own loops let’s take a moment to develop an appreciation for loops. The best way to do that is by showing you how cumbersome it would be if a repeated task required you to type …
- 3Instead of writing out the same code over and over, loops allow us to tell computers to repeat a given block of code on its own. One way to give computers these instructions is with a for loop. T…
- 4What if we want the for loop to log 3, 2, 1, and then 0? With simple modifications to the expressions, we can make our loop run backward! To run a backward for loop, we must: * Set the iterator va…
- 5for loops are very handy for iterating over data structures. For example, we can use a for loop to perform the same operation on each element on an array. Arrays hold lists of data, like customer n…
- 6When we have a loop running inside another loop, we call that a nested loop. One use for a nested for loop is to compare the elements in two arrays. For each round of the outer for loop, the inne…
- 7You’re doing great! We’re going to teach you about a different type of loop: the while loop. To start, let’s convert a for loop into a while loop: // A for loop that prints 1, 2, and 3 for (let cou…
- 8In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do…while statement comes in. A do…while statem…
- 9Imagine we’re looking to adopt a dog. We plan to go to the shelter every day for a year and then give up. But what if we meet our dream dog on day 65? We don’t want to keep going to the shelter for…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory