JS Loops

JavaScript Loops: Control Flow & Iteration

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!

What You Will Learn About Loops

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.


Types of JavaScript Loops

JavaScript supports several different types of loops, each suited for different scenarios. These are the different loops we will be discussing in this chapter:


A Quick Peek: The while Loop

To 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.

Syntax

while (condition) {
  // code block to be executed
}

Basic while Loop Example

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!");

Beware of Infinite Loops!

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.


Exercise

?

What is the primary purpose of using a loop in programming?