Basic JavaScript - Iterate with JavaScript While Loops - question about the outcome

So I managed to figure out the correct answer but am a little confused by the result and after running the code through VScode to double check the validity, I am still stumped.

Why is it that even though the loop condition states that, while i is greater than or equal to 0, the resulting array stops at 0 instead of going to -1?

Surely if the loop can still run while i = 0 then the array should run in a sequence of 5, 4, 3, 2, 1, 0, -1 but this isn’t the case and instead it simply stops at 0.

Am I missing something obvious or did I forget an important rule about arrays?

Here’s my code for reference:

// Setup

const myArray = [];

let i = 5;

while (i <= 0) {
  ourArray.push(i);
  i--;
} ```

I think you have some typos in this code here? The array doesn’t have a consistent name with how you defined it. Also, the loop will never run as you wrote it.

Sorry, just realised i uploaded the wrong one while i was halfway through editing it.

const myArray = [];
let i = 5;

while (i >= 0) {
  myArray.push(i);
  i--;
}
console.log(myArray)

So here, the condition is checked before the body runs, so the body only runs when i >= 0. It will not run if i < 0.

See that’s where I’m confused, surely in order for i to become less than 0 the loop would have to run again so that i would become -1.

The only other reason i can think of for this is that the loop is iterating through the different values of the array and since the first value within an array is in position 0, the value of i can go no lower.

The value of i is decreased inside of the loop body. So when i === 0, then the loop body executes. In the loop body, i is pushed onto myArray, and then i is decreased to i === -1. Then the loop doesn’t run again.

So is it best to assume that a while loop will stop running if the result of said loop falls outside of the boolean value?

There is no need to assume. There are strict rules for how this works.

The body of the while loop only executes while the condition is true.

Ok I think I understand now so the loop will run once it hits zero but when it checks the condition again and sees that i < 0 the loop stops because the condition is no longer met, thus not running the loop again and therefore not printing the new value

1 Like

Exactly. That condition must be met

Thanks so much, sorry for any inconvenience this might’ve caused

No inconvenience at all. We’re here to answer questions.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.