To understand what a loop is, think of it as a continuous errand you send someone on until a condition is met or they complete the task they're doing. If you don't tell the person when to stop, they might just keep going!
The computer doesn't have a human brain that allows it to pause, look at you, and ask, "When should I stop running?" It doesn't get tired. It just keeps doing its work until you tell it to stop or the task is completed. A loop that never stops is called an infinite loop, and we’ll see how it can happen in the while loop section.
The two types of loops we'll look at are the for loop and the while loop.
The For Loop
Think of the for loop as a worker with a bag of items. You give him the bag because you're just too tired to go through it yourself. You tell him how many items are in the bag and ask him to go through them from the top to the bottom, placing each item on the table in front of you.
The worker picks up the bag and takes out each item, one after another, placing it on your table. Once he's done with every item, he smiles at you, says goodbye, and goes off to his next task.
That's how a for loop works.
A for loop is commonly used to go through the elements of an array, one after another. It can also be used with other collections of data. As it goes through each item, it can print the item in your terminal, showing you what you have in your list.
You can also tell the computer to perform an action on each item as it goes through the loop. You do this by adding statements inside the loop. For example, you could add numbers together or check whether an item meets a certain condition.
Here's an example:
const bag = ["book", "ball", "apple", "shoe"];
for (let i = 0; i < bag.length; i++) {
let item = bag[i];
console.log("Placing the " + item + " on the table.");
if (item === "ball") {
console.log("Oh, there's the ball!");
}
}
This prints every item in the bag, and the worker also notices when he picks up the ball.
-
let i = 0initializes theivariable, which keeps track of the index of the item we're picking up. We start at 0 because array indexes begin at zero. -
i < bag.lengthtells the computer to keep running the loop as long asiis less than the number of items in the bag. This is the "This is where you tell him how many items are in the bag." part. The worker doesn't decide when to stop; the count does. -
i++increasesiby one after each round, so the worker moves on to the next item. -
let item = bag[i]stores the current item in theitemvariable so we can work with it. -
console.log("Placing the " + item + " on the table.")is the worker placing the item on your table. -
if (item === "ball")checks whether the current item is a ball. If it is, the computer prints "Oh, there's the ball!" and then carries on to the remaining items.
When i reaches 4 (the number of items), the condition i < bag.length is no longer true, and the loop ends. The bag is empty.
Other ways to write a for loop in JavaScript
The loop above is the classic for loop. JavaScript has a few shorter versions for going through arrays. The most common is for...of, which hands you each item directly, so you don't need i:
for (const item of bag) {
console.log("Placing the " + item + " on the table.");
}
The While Loop
The while loop works almost the same way as the for loop, but there's a slight difference. In fact, a for loop is really a while loop with the starting point, the condition, and the update all packed into one line.
Let's imagine the same worker again, but with a different job. This time, you send him to the market to buy some oranges.
You don't know where the orange stall is, so you can't give him a count like you did with the bag. Instead, you tell him: "Keep looking around the market until you find it." Each time he checks a stall, he has to decide: is this the orange stall yet? Once he finds it, he can buy the oranges and stop searching.
That's the idea behind a while loop: keep going while the answer is still "not yet."
To do this, the computer needs something it can check every round. Think of it as a yes/no question: "Have I found the orange stall?"
- At the start, the answer is no (
false), because the worker hasn't found it yet. - While the answer is still no, the loop keeps running.
- The moment the worker finds the stall, the answer changes to yes (
true), and the loop stops.
Here's an example:
let orange_stall = false;
let stallsChecked = 0;
while (!orange_stall) {
stallsChecked++;
if (stallsChecked === 3) {
orange_stall = true;
console.log("Stall " + stallsChecked + " sells oranges!");
} else {
console.log("Stall " + stallsChecked + " isn't it. Still looking...");
}
}
console.log("I've found the orange stall! Now I can buy the oranges.");
This prints:
Stall 1 isn't it. Still looking...
Stall 2 isn't it. Still looking...
Stall 3 sells oranges!
I've found the orange stall! Now I can buy the oranges.
-
let orange_stall = falsemeans "Have I found the orange stall?" The answer starts as no, because the worker hasn't found it yet. -
let stallsChecked = 0keeps count of how many stalls he has checked. -
while (!orange_stall)tells the computer to keep running the loop as long as the stall is not found. The exclamation mark (!) means "not," so!orange_stallreads as "the orange stall has not been found." While that's true, the worker keeps searching. - Inside the loop, the worker checks one more stall each round (
stallsChecked++). If it's the third stall, we setorange_stalltotrue, which means "yes, found it." Otherwise, he keeps looking. - Once
orange_stallistrue, then!orange_stallbecomes false, so the loop stops. Then the computer prints "I've found the orange stall! Now I can buy the oranges."
Of course, this is a simplified example. We used stallsChecked === 3 to stand in for the worker spotting the stall. In a real program, the computer would check something real, like whether the stall's sign says "Oranges."
A word of warning: what if the worker never finds the stall? If nothing inside the loop ever sets orange_stall to true, the answer stays "not found" forever, and the loop never stops. That's an infinite loop. It's the worker wandering the market for eternity, so always make sure something inside your while loop can eventually make the condition false.
The Main Difference
The main difference is how we decide when the loop should stop.
With a for loop, the stopping point is built into the setup. You know what you're going through (a bag with a known number of items) or how many times to repeat, and the loop ends when it gets there.
With a while loop, the stopping point depends on something happening along the way. You don't know how many times the loop will run, only what condition will end it. The worker makes a judgment at each step: "Have I found it yet?"
Both loops can be useful, depending on what you want your program to do.
I hope you found this helpful.
It's been a while since my last post in this series. I'm not totally back yet, but I'm popping in to complete the series I started for beginner developers.
Before you go, here's a quick question: think of something you do every day. Is it more like a for loop (a known list of things to do) or a while loop (repeating until something changes)? Tell me in the comments.
Top comments (0)