Javascript Loops Quiz Question: Infinite Loops

Hey guys!

I’m going through the CodeCademy Javascript “Loops” Quiz, and am having difficulty understanding the concept of Infinite Loops.

I don’t understand how the code below results in an infinite loop, due to the stopping condition not existing.

Code:

for (let i = 10; i > 0; i++) {
console.log(i);
};

The way I understood it, i = 10 is the initialization, which means the loop starts counting at 10.

The stopping condition is i > 0.

However, if we start counting at 10 and go upwards by 1 from there, won’t i always be greater than 0?

In other words, how does the loop even get started when it’s stopping condition is satisfied by the very first loop?

If it was the opposite stopping condition , I < 0, then I could see why it would be an infinite loop, since it’s starting at 10 and going upwards, and i will never be less than 0.

I’m clearly misunderstanding this fundamental concept lol - any guidance or thoughts are super appreciated!

Operative words in your question are, stopping condition. In truth, the condition allows continuation. Think in terms of, while i > 0 keep doing this.

We are told in some narratives that the second parameter of a `for` statement is a stopping condition. Clearly that is a misnomer. As stated, the condition is simply allowing the code to run until such time as the condition is no longer met. Running condition flip flops the stopping notion.

``````if condition then stop

if condition then continue
``````

A for loop uses the latter. The former would be a stopping condition.

This makes sense, I understand where I went wrong in my logic now. Thank you for the amazing and prompt response!

1 Like

You’re welcome.

Expect binary decisions like this to come up a lot. MDN is our friend when in doubt.

3 Likes