Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Evelina Monroe
Evelina Monroe
7,156 Points

"What are Loops?" video in the beginning, he says a loops is a way to repeat the same thing over until condition is true

In the "What are Loops?" video in the beginning, he says a loop is a way to repeat the same thing over until condition is TRUE...but shouldn't it be it runs over and over until a certain condition is no longer true? This really threw me off. In the example in the previous video, the counter runs over and over until the condition is no longer true. But in this video he says the condition will run over and over until it is true. Kinda confusing.

Good catch Evelina, I didn't even notice he said that on my first run through the video.

2 Answers

Jarrad O'Brien
Jarrad O'Brien
8,136 Points

It can be either. It's possible to write a loop where it only stops when a condition is false OR you can write a loop where it only stops when a condition is true.

So yeah, when your counter goes over a certain number the condition becomes false and that's why it stops. For example, "run this loop as long as the counter is less than or equal to 10". When the counter goes from 10 to 11, the condition is false and the loop stops. But you could also write a condition where you say, "run this loop until the counter is greater than or equal to 10". When the counter goes from 9 to 10, the condition is true and the loop stops.

rydavim
rydavim
18,771 Points

Here's an example of a loop:

for (i = 0; i < 10; i++) {
  console.log(i + " is still less than 10. (True)");
};

Normally, you would think of this as running until the expression in the middle is no longer true, and that would be a good way of thinking about it.

However, colloquially you could also think of the loop as running until i is equal to 10. That might be what Dave McFarland meant, but maybe he can drop by and clarify.