I need help I'm stuck on JavaScript While loops

Tell us what’s happening:
var i = 0;

while(i < 6) {

myArray.push(i);

i++;

}

console.log(myArray)

Your code so far


// Setup
var myArray = [];

// Only change code below this line
var i = 0;
while(i < 6) {
myArray.push(i);
i++;
}
console.log(myArray)

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS armv7l 13020.87.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.119 Safari/537.36.

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

Hi and welcome to the forum.

It looks like you mostly have the right idea, but you are putting the numbers in in increasing order.

I’d look at changing i from increasing to decreasing on each iteration.

To do this you will need to change the initial value of i, the loop exit condition, and the second line inside your loop.

I hope this helps!

1 Like

can you explain to me

If we log your array after the code has run we get this:

console.log(myArray) // [ 0, 1, 2, 3, 4, 5 ]

This is the test requirement:

myArray should equal [5,4,3,2,1,0].

1 Like

@Jahod1 Try examining the example given in the lesson before attempting the challenge. The code in the example starts the loop from 0 and adds 1 every time until the while condition is not valid anymore. For the challenge, what you need to do is the opposite. You should start from the top (which is 5) and loop through until you reach 0 (inclusive) - count downwards and add them into the ‘myArray’! So first push number 5 into ‘myArray’, then number 4, and so on.
I hope that is clear!

1 Like

var i = 6;
while(i < 5) {
myArray.push(i);
i++
}

that will never run

notice how your i starts at 6 but the loop condition is i < 5

that means that it is false even before going to the loop and the loop never run

idk lol i try everything var i = 0;
while(i < 6) {
myArray.push(i);
i++
}

console.log(myArray)

now you are back to making the numbers go up

think about it, how do you count from 5 to 0?

you start at five, decrease by one each time, and then when do you stop?

The statement i++ means ‘increase i by 1’. You need to make i decrease. Do you remember a freeCodeCamp challenge showing you how to make a variable decrease?

var i = 5;

while(i >= 0) {

myArray.push(i);

i++

}

console.log(myArray)

now you got an infinite loop because you start from 5, than keep increasing i with i++, and i >= 0 will always be true

if you start at 5 and wants to go down to 0 you need to decrease the value of i

var i = 5;

while(i >= 0) {

myArray.push(i);

i–

}
thanks got it

2 Likes

awesome! Happy coding!