While Loops and Iteration

In the code below I am trying to get the numbers 5 through 0 inclusive pushed to my array. However I can not get the value 0 pushed to my array. I do not understand why.

1 is greater than 0, so why doesnt the code substract 1 from 1 and then push 0 to myArray.

Below is a link to the challenge I got this from and trying to solve / understand.

const myArray = [];

let i = 5;
while (i>0){

Iterate with JavaScript While Loops


Because you don’t include to zero on your while condition. How you can make it work while is zero not just grater than zero?

Hi, thanks for responding to my question.

What do you mean include 0 in the while conedition ? I said while i > 0 in the condition. Could you provide more detail in your repsonse please.

This i>0 mean ‘i’ grater than zero but can’t equal to zero. If you don’t remember of the logical operators on js, no problem you can look at this documentation.

Thank you for the link. That was very helpful. I know what i > 0 means.

But it still doesnt explain my question.

The loop is meant to check that the last number is greater than 0 then subtact 1.

1 is greater than 0 so why does it not subtract 1.

Or are you saying that the condition does not just apply to the loop but the contents of the array ? Meaning the array is subject to the condition and values that do not pass the condition can not be pushed to the array ? Cause that would make more sense I think.

I think you should add some console statements here to better understand what your code is doing

// Setup
const myArray = [];

// Only change code below this line

let i = 5;
while (i > 0) {
  console.log("This is i before push: ", i)
  console.log("This is i after push: ", i)

what you are going to see is that when i is 1, then 1 gets pushed to myArray.
Then i is decremented here i--
So now, i is 0

When the condition is checked again (0>0), 0 is not greater than 0 so the while loop stops and i is no longer pushed to myArray

So you need to use a different operator here

hope that clears it up

So the order will always be as follows

if condition is true i>0

  • push i to myArray
  • decrement i by 1
  • check the condition again

The second the condition becomes false, then the while loop stops running.
So i does become 0, but then the condition is checked again before push is used again.
Since 0 is not greater then 0, then push never happens again