Change the order

Tell us what’s happening:
I am using “while” to make a loop, but the result is [0,1,2,3,4,5], where as the question requires [5,4,3,2,1,0]
So how can I change the order of numbers?
Your code so far*


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

i++;
}
console.log();

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:

maybe use unshift …

When you type var i = 0; you are telling javascript to create a variable called i and set it to 0 (zero).

Then, inside your while loop, you say i++ each time it loops. So each time it will add 1 to i, and save i with that new value.

It will keep doing this as long as (“while”) i <= 5

So: Starting from zero, i will take on the values: 0, 1, 2, 3, 4, and 5.

The challenge here is to find a way to start from 5, and go backwards!

Let us know if you would like another hint or a better explanation of how the loop works :slight_smile:

Good luck!

1 Like

unshift doesn’t work, I’ve tried that.

I’ve already tried that, it doesn’t work. I guess there must be a kind of “count down” code that I haven’t learned yet.

what have you tried with unshift?


no, you already know everything, it’s just a matter of using the stuff you know in the right way, to count downward instead of upward

There is no such thing as count up or count down in programming I’m afraid. It’s just procedure steps that you can control:

STEP 1. CREATE NUMBER
STEP 2. CHECK IF NUMBER SATISFIES CONDITION
STEP 3. PUSH NUMBER TO ARRAY
STEP 4. CHANGE NUMBER
STEP 5. GO TO STEP 2

Now in order to get countdown from 5 to 0, think what would be the number in step 1, condition in step 2 and how are you going to change number in step 4.

Screenshot at Jun 11 10-10-14

Works very well.
I cannot believe that this is an exercise that creates confusion, wait for recursion and asynchrony.

Another way of doing things.

Screenshot at Jun 11 10-17-22