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