Issues with 'while' loops

Tell us what’s happening:
I don’t understand why this code isn’t working… it comes up with the correct [0, 1, 2, 3, 4] output but then gives me an error message of ‘myArray should equal [5,4,3,2,1,0]’.

I don’t know why my code so far isn’t working - I have watched the tutorial video and the code is exactly the same. Can anyone please advice what I’m 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++;
}

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/83.0.4103.61 Safari/537.36.

Challenge: Iterate with JavaScript While Loops

Link to the challenge:

Hi @zenayounis9 and welcome to the forum! Looking at the above I doubt output [0, 1, 2, 3, 4] would be something I call “correct”.

Challenge description is asking to put numbers “in descending order”. Think what would be your initial value of i and how would you change it in order to get numbers in descending order.

1 Like

Hello @snigo, thank you so much for your speedy reply! As you were typing I realised my error and managed to pass the code with the following:

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

1 Like