Iterating javascript with loops

Tell us what’s happening:
Describe your issue in detail here.
hello everyone, I cannot get my codes to produce [ 5, 4,3,2,1,0]. how should i go about it? And if you have other resources on understanding javascript loops kindly share it

   **Your code so far**

// Setup
const myArray = [];

// Only change code below this line

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

console.log(myArray);
   **Your browser information:**

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

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

Why 1++?

Since you are not changing i, this will loop forever.


You have some of the pieces you need here.

Your loop needs to use the numbers from 0 to 5. Your loop needs to put numbers in an array in the right order. Let’s start with getting the loop to go through 0 to 5. How do you do that?

1 Like

Thanks :+1:
I finally figured it out

**My code **

// Setup
const myArray = [];

// Only change code below this line

var i = 5;
while(i >= 0) {
 myArray.push(i);
i--;
}

console.log(myArray);

That’s all :blush:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

Hi @Olalekan20 !

The last code you posted still has a couple of errors.
Did you still need help?

1 Like

Please do put me through
My laptop just had a flat battery now but I guess I can use my phone

The first issue here

If i<=0 then the condition will never be true because 5 is never going to be less than 0.
You need to change your condition so the while statement is true.

For here,

you don’t want to decrement 1 but instead decrement i.
When you decrement i, that is how you get 5,4,3,2,1,0

Hope that makes sense!

Thanks for the help
My JavaScript still sucks thou but I will soon catch up :blush::blush:

Glad to help.
JavaScript takes some time to learn so it is completely normal to stumble on challenges

2 Likes