We are starting to get a good basic grasp of JavaScript. This chapter will focus on a very important control flow concept: loops.
Loops execute a block of code a certain number of times.
We can use loops to do many things, such as:
Whenever you feel the need to copy a little piece of code and paste it multiple times, you should probably be using a loop instead!
We will first discuss the basics of loops. Then, we will continue to discuss nesting loops, which means using loops inside of other loops.
We will also explain looping over two complex constructs we have seen: arrays and objects.
Finally, we will introduce two keywords related to loops—break and continue—to control the flow of the loop even more.
Note on forEach: There is one topic closely related to loops that is not in this chapter: the built-in forEach method. We can use this method to loop over arrays, typically using an arrow function. Since we won't discuss functions until the next chapter, forEach is not included here.
JavaScript supports several different types of loops, each suited for different scenarios. These are the different loops we will be discussing in this chapter:
while loop: Loops through a block of code as long as a specified condition is true.do...while loop: Also loops through a block of code while a specified condition is true, but executes the code block at least once before checking the condition.for loop: Loops through a block of code a specific number of times.for...in loop: Loops through the properties of an object.for...of loop: Loops through the values of an iterable object (like an array).while LoopTo get started, let's look at the most fundamental loop: the while loop. It repeats a block of code as long as the specified condition evaluates to true.
while (condition) {
// code block to be executed
}
let count = 1;while (count <= 5) { console.log("Iteration number: " + count); count++; // Don't forget to increment, or the loop will run forever! } console.log("Loop finished!");
When writing a while loop, you must ensure that the condition will eventually evaluate to false.
If it doesn't (for example, if you forget to include count++ in the example above), the loop will run forever! This will freeze or crash the user's browser.
What is the primary purpose of using a loop in programming?