Basic JavaScript: Iterate with JavaScript While Loops (General Question)

I passed it with the code below but there has to be a way to push numbers in a descending order without multiple .push() statements?

Your code so far

// Setup
var myArray = [];

// Only change code below this line
var i = 5;
while (i < 6) {


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36.

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

You didn’t really use a loop, you set the loop bounds to only execute the loop body once.

In order to make a loop that pushes values in descending order, you should make your iteration variable i decrease.

Hi! @anonbubble,

If you want a descending order of i, you have to first print 5, then 4, then 3 …, that means each time it prints a number it will reduce the value of i, that is i-1
or i--

but how long? you have to stop at 0 as test expected, that means when it equals/reaches to 0, your code should stop, right?

How to make that? see this example:

var collectedArray=[];
var x = 10;
// x starts from 10

//now using while
while (x>=0){
// it means each time it will work until it meets the condition 
// x  greater than or equal to 0 (inclusive 0)
// so when it starts countdown from 10, once it will reach to 0,
// then it will stop counting as per condition
// our fist condition meets to 10 that is >=0
// so we'll push this value to our store, named collectedArray

// as we need to print then 9, we need to reduce the value of i
 // that 's all, it will stop when it will reach to 0
// everything between 10 and 0 will be collected

Hope, you will get a clear concept by this, and you can also apply this in the future where necessary.

Thank you,

Your code has been blurred out to avoid spoiling an essentially full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a nearly full passing solution to a challenge, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


You didn’t have to type multiple push statements for your code to work.
The mistake you made was on this line
while (i < 6)
Your I value just increases once and the while loop stops running because it is now 6.
a better way would be to initialise I = 0, and then decrease I by one until it gets to 0. something like this .
while (0 > I)
Then you log in the values of the I (i.e you must have a i-- in your code) .

1 Like

Ahh, I was thinking that the while (x>=0) is how many times the loop will iterate. I was putting the same value in the array and the variable. I appreciate the detailed explanation!

1 Like