While loop.. what am I doing wrong?

Tell us what’s happening:
what am I doing wrong?

Your code so far


// Setup
var myArray = [];

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

the output of your code will be [0,1,2,3,4] but the expected output should be [5,4,3,2,1,0]

1 Like

So if you reverse this logic

and count down from 5 instead of up you will get the correct answer.

// Setup

var myArray = [];

// Only change code below this line

var i = 5;

while(i < 0) {

myArray.push(i);

i++;

}

Like this??

This part is right

For here, the condition doesn’t make sense.

If i is 5, 5 is not less than 0 so the while loop never executes.
Try rewriting this part so the condition makes sense.

We want to say , when i is greater than or equal to 0.

Also this part needs to be changed.

If we are counting down, it would be better to decrement instead of increment, right?

1 Like

You have to decreament to get the required
[5,4,3,2,1,0]

Varable i should decrement from 5

Instead of ++ incrementing from 0

And

Make sure your condition is such that it relate with the new decrement so that you don’t end up in an infinite loop

1 Like

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Okay noted.

I’ll try maintaining that standards

This post was flagged by the community and is temporarily hidden.

This post was flagged by the community and is temporarily hidden.